Python OpenCV (Open Source Computer Vision Library) is a powerful tool for image and video processing. It provides a wide range of functions for tasks like image manipulation, object detection, facial recognition, and more. OpenCV is widely used in various industries, including robotics, healthcare, and automotive.
How OpenCV Works
OpenCV works by using algorithms to process images and videos. It can perform tasks such as detecting edges, recognizing shapes, and tracking objects in real-time. OpenCV uses computer vision techniques to analyze and interpret visual data, allowing developers to create applications that can “see” and understand the world around them.
Key Features of OpenCV
Image Processing: OpenCV can perform various operations on images, such as resizing, cropping, and filtering.
Object Detection: It can detect objects in images and videos using techniques like Haar cascades and deep learning.
Facial Recognition: OpenCV can recognize faces in images and videos, allowing for applications like face detection and face tracking.
Real-time Processing: OpenCV can process images and videos in real-time, making it suitable for applications that require immediate feedback, such as augmented reality and robotics.
Machine Learning: OpenCV integrates with popular machine learning libraries like TensorFlow and PyTorch, allowing developers to build complex models for image analysis and classification.
Example 1: How to open the image using OpenCV and matplotlib library in a Python program: Don’t forget to add your own image path
# Import OpenCV module
import cv2
# Import pyplot from matplotlib as pltd
from matplotlib import pyplot as pltd
# Opening the image from files
imaging = cv2.imread("open.png")
# Altering properties of image with cv2
img_gray = cv2.cvtColor(imaging, cv2.COLOR_BGR2GRAY)
imaging_rgb = cv2.cvtColor(imaging, cv2.COLOR_BGR2RGB)
# Plotting image with subplot() from plt
pltd.subplot(1, 1, 1)
# Displaying image in the output
pltd.imshow(imaging_rgb)
pltd.show()
Output:


Explanation of the above code:
import cv2: This line imports the OpenCV module, which is used for computer vision tasks, such as image and video processing.from matplotlib import pyplot as pltd: This line imports thepyplotmodule from thematplotliblibrary and renames it aspltd.pyplotis used for creating visualizations like plots and graphs.imaging = cv2.imread("open.png"): This line reads an image file named “open.png” and stores it in the variableimaging.img_gray = cv2.cvtColor(imaging, cv2.COLOR_BGR2GRAY): This line converts the color image (imaging) to grayscale (img_gray) using thecvtColorfunction from OpenCV.imaging_rgb = cv2.cvtColor(imaging, cv2.COLOR_BGR2RGB): This line converts the color image (imaging) from BGR (Blue-Green-Red) to RGB (Red-Green-Blue) format. This step is necessary because OpenCV reads images in BGR format, whileimshowexpects RGB format for display.pltd.subplot(1, 1, 1): This line creates a subplot with 1 row, 1 column, and selects the first subplot. Subplots are used to display multiple plots in a single figure, but in this case, there’s only one subplot.pltd.imshow(imaging_rgb): This line displays the image (imaging_rgb) in the selected subplot. Theimshowfunction is used to show images inmatplotlib.pltd.show(): This line displays the image plot. It’s important to useshow()to actually display the plot, otherwise, it won’t be visible.
Now, How to Recognize/Detect an object of red colour detection in the image ?
For this, we will use the detectMultiScale() in the program to detect the object present in the image. Below is the syntax for using detectMultiScale() function in the code:
found = xml_data.detectMultiScale(img_gray,
minSize = (30, 30))
Full Code for object detection in a image using openCv
import cv2
import numpy as np
# Load the input image
image = cv2.imread('open.png')
# Convert the image to HSV color space
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# Define the lower and upper bounds of the red color (in HSV)
lower_red = np.array([0, 100, 100])
upper_red = np.array([10, 255, 255])
# Create a mask for the red color
mask = cv2.inRange(hsv, lower_red, upper_red)
# Find contours in the mask
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Draw bounding boxes around the detected objects
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
# Display the image with bounding boxes
cv2.imshow('Object Detection', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output:

Explanation of the above code:
import cv2: Imports the OpenCV library for image processing.import numpy as np: Imports the NumPy library for numerical operations.image = cv2.imread('open.png'): Loads the image ‘open.png’ from the current directory.hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV): Converts the BGR image to the HSV color space.lower_red = np.array([0, 100, 100])andupper_red = np.array([10, 255, 255]): Define the lower and upper bounds of the red color in HSV.mask = cv2.inRange(hsv, lower_red, upper_red): Creates a binary mask for the red color in the image.contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE): Finds contours in the binary mask. Contours are continuous lines or curves that bound or cover the full object in the image.for contour in contours:: Iterates over each contour found.x, y, w, h = cv2.boundingRect(contour): Calculates the bounding rectangle for the contour.cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2): Draws a green rectangle around the detected object.cv2.imshow('Object Detection', image): Displays the image with bounding boxes.cv2.waitKey(0): Waits indefinitely for a key press.cv2.destroyAllWindows(): Closes all OpenCV windows.
Conclusion:
Python OpenCV is a versatile library that provides a wide range of tools for image and video processing. Whether you’re working on a simple image manipulation task or a complex computer vision project, OpenCV can help you achieve your goals. Its ease of use and powerful features make it a valuable tool for developers and researchers alike.





Leave a Reply