How to Detect Humans in an Image in OpenCV Python?
With the advancements in computer vision technology, it has become possible to detect humans in images using OpenCV in Python. OpenCV is a library that enables the processing of images, videos, and other multimedia files. It provides many features such as image processing, object detection, and more.
In this article, we’ll discuss how to detect humans in an image using OpenCV in Python.
Setting Up Environment
First, we need to set up the environment and install the necessary libraries. Run the following lines in the command prompt to install OpenCV and imutils.
pip install opencv-python
pip install imutils
Now, we’re ready to write the code.
Loading an Image
Let’s start by loading an image that contains humans in it. For this example, we’ll use the ‘person.jpg’ image. To load the image, we’ll use the cv2.imread() function.
import cv2
image = cv2.imread('person.jpg')
cv2.imshow('Image', image)
cv2.waitKey(0)
In the code above, we’ve imported the cv2 library and loaded the image using the imread() function. We then display the image using the imshow() function. cv2.waitKey(0) waits for any key event to occur.
Human Detection
Once we’ve loaded the image, we can detect humans using OpenCV’s built-in function: Human Detector. This detector uses pre-trained classifiers to detect humans in an image.
import cv2
image = cv2.imread('person.jpg')
human_cascade = cv2.CascadeClassifier('haarcascade_fullbody.xml')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
humans = human_cascade.detectMultiScale(gray, 1.1, 4)
for (x, y, w, h) in humans:
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow("Human Detection", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
In the code above, we’ve applied the human detector to the image. The cv2.CascadeClassifier()
function loads a pre-trained classifier, which is stored in the XML file. We use cv2.cvtColor() function to convert the image to grayscale. The detectMultiScale() function detects humans in the grayscale image.
After we detect the humans, we’ll draw the bounding boxes around them. We use the cv2.rectangle() function to draw the bounding box. Finally, we show the image.
We use cv2.destroyAllWindows() function to destroy all the windows we’ve created.
Conclusion
We’ve learned how to use OpenCV in Python to detect humans in an image. This technology can be used for various purposes such as security surveillance, detecting illegal activities, and much more.
OpenCV can be used in many other applications apart from human detection. So, it is essential to explore and learn more about this technology.