Detect an object with OpenCV-Python
Last Updated :
13 Aug, 2024
OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human. This article focuses on detecting objects.
Note: For more information, refer to Introduction to OpenCV.
Object Detection
Object Detection is a computer technology related to computer vision, image processing, and deep learning that deals with detecting instances of objects in images and videos. We will do object detection in this article using something known as haar cascades.
Haar Cascades
Haar Cascade classifiers are an effective way for object detection. This method was proposed by Paul Viola and Michael Jones in their paper Rapid Object Detection using a Boosted Cascade of Simple Features. Haar Cascade is a machine learning-based approach where a lot of positive and negative images are used to train the classifier.
- Positive images – These images contain the images that we want our classifier to identify.
- Negative Images – Images of everything else, which do not contain the object we want to detect.
Steps to download the requirements below
Note: Put the XML file and the PNG image in the same folder as your Python script.
Implementation
Image used
Opening an image
Python
import cv2
from matplotlib import pyplot as plt
# Opening image
img = cv2.imread("image.jpg")
# OpenCV opens images as BRG
# but we want it as RGB and
# we also need a grayscale
# version
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Creates the environment
# of the picture and shows it
plt.subplot(1, 1, 1)
plt.imshow(img_rgb)
plt.show()
Output:
Recognition
We will use the detectMultiScale()
function of OpenCV to recognize big signs as well as small ones:
Python
# Use minSize because for not
# bothering with extra-small
# dots that would look like STOP signs
stop_data = cv2.CascadeClassifier('stop_data.xml')
found = stop_data.detectMultiScale(img_gray,
minSize =(20, 20))
# Don't do anything if there's
# no sign
amount_found = len(found)
if amount_found != 0:
# There may be more than one
# sign in the image
for (x, y, width, height) in found:
# We draw a green rectangle around
# every recognized sign
cv2.rectangle(img_rgb, (x, y),
(x + height, y + width),
(0, 255, 0), 5)
Here is the full script for lazy devs:
Python
import cv2
from matplotlib import pyplot as plt
# Opening image
img = cv2.imread("image.jpg")
# OpenCV opens images as BRG
# but we want it as RGB We'll
# also need a grayscale version
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Use minSize because for not
# bothering with extra-small
# dots that would look like STOP signs
stop_data = cv2.CascadeClassifier('stop_data.xml')
found = stop_data.detectMultiScale(img_gray,
minSize =(20, 20))
# Don't do anything if there's
# no sign
amount_found = len(found)
if amount_found != 0:
# There may be more than one
# sign in the image
for (x, y, width, height) in found:
# We draw a green rectangle around
# every recognized sign
cv2.rectangle(img_rgb, (x, y),
(x + height, y + width),
(0, 255, 0), 5)
# Creates the environment of
# the picture and shows it
plt.subplot(1, 1, 1)
plt.imshow(img_rgb)
plt.show()
Output :
Detect an object with OpenCV-Python – FAQs
How to Detect Objects Using OpenCV Python
Object detection using OpenCV in Python can be performed using several methods, with one of the most common being the use of the Haar Cascade Classifier. This method involves using pre-trained classifiers for detecting objects like faces, eyes, or vehicles.
Steps to Detect Objects with Haar Cascade Classifier:
- Import Necessary Libraries: You need to import OpenCV.
import cv2
- Load Pre-trained Classifier: OpenCV provides several pre-trained classifiers, which can be loaded using
cv2.CascadeClassifier
.
# Load a pre-trained face detector classifier
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
- Read the Image: Load the image where you want to detect objects.
image = cv2.imread('path_to_image.jpg')
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Convert to grayscale
- Detect Objects: Use the classifier to detect objects in the image.
faces = face_cascade.detectMultiScale(gray_image, scaleFactor=1.1, minNeighbors=5)
- Draw Rectangles Around Detected Objects: For each detected object, draw a rectangle around it.
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (255, 0, 0), 2)
- Display the Result:
cv2.imshow('Detected Faces', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
How to Use OpenCV to Detect Objects in Image and Track Them Over Time
For tracking objects over time in video streams or video files, you can use the combination of object detection (using methods like the Haar Cascade) followed by object tracking algorithms provided by OpenCV, such as KCF, TLD, or MIL.
- Detect the Object in the First Frame: Use any object detection method to locate the object in the first frame.
- Initialize the Tracker: Once the object is detected, initialize a tracker with the object’s position.
- Update Tracker for Each New Frame: For each new frame in the video, update the tracker to find the object’s new position.
# Initialize tracker
tracker = cv2.TrackerKCF_create()
init_box = None # Assuming init_box is the bounding box of detected object
video = cv2.VideoCapture('video_path.mp4')
# Read first frame
ok, frame = video.read()
if ok:
init_box = cv2.selectROI(frame, False) # Let user select ROI
tracker.init(frame, init_box)
while True:
ok, frame = video.read()
if not ok:
break
ok, bbox = tracker.update(frame)
if ok:
(x, y, w, h) = [int(v) for v in bbox]
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2, 1)
else:
cv2.putText(frame, "Tracking failure", (100, 80), cv2.FONT_HERSHEY_SIMPLEX, 0.75,(0,0,255),2)
cv2.imshow("Tracking", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video.release()
cv2.destroyAllWindows()
How Do You Count the Number of Objects in an Image Using OpenCV Python?
To count the number of objects in an image using OpenCV, you can follow the detection steps and simply count the number of detected instances.
- Detect Objects: As shown previously with the Haar Cascade or any other detection method.
- Count: The length of the list of detections gives the count of objects.
# Continuing from the face detection example
num_faces = len(faces)
print(f"Number of faces detected: {num_faces}")
These methods and steps provide a robust framework for incorporating object detection and tracking functionalities in your applications using Python and OpenCV