Quick and easy image recognition with 9 lines of code in Python

5 May 2024

This is how you can create a simple image recognition script in Python. You'll need the following packages to run the script:
opencv-contrib-python
cvlib
pillow
tensorflow
Put them in your requirements.txt and install them with pip install -r requirements.txt. The script in its entirety can be seen here:
import cv2
import cvlib as cv
from cvlib.object_detection import draw_bbox
from PIL import Image

img = cv2.imread(DJI_0040.JPG)

bbox, label, conf = cv.detect_common_objects(img)
output_image = draw_bbox(img, bbox, label, conf)

im = Image.fromarray(output_image)
im.save(DJI_0040_labels.JPG)
Simply change the filename to your file, and you are good to go. Below you can see an example of the input and output of the program.
Image without image recognition

Input image.

Image with image recognition

Output image with detected items marked.

The labels of all the identified objects are saved as a list to the variable label. In my example the label list includes 8 boats and 3 cars.
['boat', 'boat', 'boat', 'boat', 'boat', 'boat', 'boat', 'boat', 'car', 'car', 'car']
There you go. Image detection doesn't get more simple than that.

Happy coding!

You might also enjoy

Removing EXIF data from an image using Python

Removing EXIF data from an image using Python

Published 2024-09-18 — Updated 2024-11-21

Python

EXIF data is information that is embedded within digital images and is automatically generated by digital cameras and smartphones.

Read the post →
How to easily web scrape any website with Python

How to easily web scrape any website with Python

Published 2024-05-03

Datahoarding

Notes

Python

Web development

Learn how to easily web scrape any website using Python. I go through the various techniques I use.

Read the post →
Python notes

Python notes

Published 2024-05-03 — Updated 2024-05-14

Notes

Python

Different tips, tricks and how-to's while developing various scripts in Python.

Read the post →