04 Optional: Using DataBouncer with OpenCV

04 Optional: Using DataBouncer with OpenCV#

OpenCV is a popular library to process images and videos. In this short guide we will show how to use it with DataBouncer by embedding this image:

matterhorn1.jpg

Project Setup#

The setup is similar to the other guides.

  • Inside of the existing getting_started folder create a new folder 04_using_opencv.

    mkdir -p getting_started/04_using_opencv
    
  • Right-click and download the image above into 04_using_opencv/matterhorn1.jpg

After completing this guide, the folder structure will be as follows:

getting_started
├── 02_similarity_search
│   └── ...
├── 03_diversity_selection
│   └── ...
├── 04_using_opencv
│   ├── matterhorn1.jpg
│   └── main.py
└── databouncer_model_freemium_v1.tar

Note

In this example we use the model version databouncer_model_freemium_v1.tar. You might need to adjust the thresholds in this tutorial if your model version differs.

Run a Complete Example#

Create 04_using_opencv/main.py and copy the contents below into it.

import cv2
from databouncer import DataBouncer


# Initialize the DataBouncer SDK.
print("Initializing DataBouncer...")
databouncer = DataBouncer.new_from_tar(tar_path="../databouncer_model_freemium_v1.tar")

# Load the image.
bgr_array = cv2.imread("matterhorn1.jpg")
rgb_array = cv2.cvtColor(bgr_array, cv2.COLOR_BGR2RGB)

# Embed the image.
embedding = databouncer.embed_rgb_array(rgb_array=rgb_array)

print("Image embedded successfully!")
print(f"Embedding: {embedding[0]:.4f}, {embedding[1]:.4f}, {embedding[2]:.4f}, ...")

We load the image with OpenCV and convert it to RGB so that it can be processed by DataBouncer. DataBouncer provides the DataBouncer.embed_rgb_array function that returns the embedding. It accepts a 3D array of dimensions height x width x 3 encoding the image in RGB, which is compatible with the output of cv2.cvtColor.

Run it:

# Enter the project folder.
cd 04_using_opencv

# Run the Python script
python main.py

The output should be similar to the following, the embedding might slightly differ on your machine architecture:

Initializing DataBouncer...
Image embedded successfully!
Embedding: -0.5142, 1.5543, -1.9983, ...

Next Steps#

The image embedding above is a drop-in replacement that can be used for all the selection strategies of DataBouncer.

Congratulations! At this point you have completed the Getting Started guide. For more details about the available interfaces, take a look at DataBouncer API reference.