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:
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)
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

How to easily web scrape any website with Python

How to easily web scrape any website with Python

Published 2024-05-03




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



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

Read the post →
How to get the channel ID of a YouTube channel

How to get the channel ID of a YouTube channel

Published 2024-04-26


Learn how to get a Youtube channel ID the proper way.

Read the post →