Shape analysis is a fascinating and essential area in the realm of computer vision. It allows machines to understand visual information based on the shapes, enabling them to make decisions about objects, environments, and even motion. In this blog post, we will break down the key components of shape analysis and provide practical examples using Python and OpenCV.
Shape analysis involves examining the geometric properties of shapes present in images. It helps in recognizing, classifying, and interpreting objects based on their geometric structure. This analysis can be useful in numerous applications such as object detection, classification, and tracking.
Contours: A contour is a curve joining all the continuous points along a boundary that have the same color or intensity. Contours can be used to find the outline of shapes within an image.
Moments: Moments are scalar values that contain information about the shape’s geometry. They can help compute properties like the centroid, area, bounding box, and more.
Shape Descriptors: These are features extracted from the shape data that represent unique characteristics of the shapes, such as aspect ratio, circularity, and convexity.
Template Matching: A technique used to identify or match a template shape to shapes within a larger image.
To begin your journey in shape analysis with Python, you will need to ensure OpenCV is installed. If it’s not already installed, you can do so via pip:
pip install opencv-python
Once you have OpenCV set up, let’s dive into some practical code examples for shape analysis.
First, let’s load an image and detect the contours within it.
import cv2 import numpy as np # Load an image image = cv2.imread('shapes.png') gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) _, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY_INV) # Find contours contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Draw contours cv2.drawContours(image, contours, -1, (0, 255, 0), 3) # Show the result cv2.imshow('Contours', image) cv2.waitKey(0) cv2.destroyAllWindows()
In this code, we start by loading our image and converting it to a grayscale image. We then apply a binary threshold to create a binary image. The findContours
function returns the contours of the shapes which we then draw and display.
Next, we can compute shape properties like area and the centroid using moments.
for contour in contours: # Calculate moments M = cv2.moments(contour) if M["m00"] != 0: cX = int(M["m10"] / M["m00"]) cY = int(M["m01"] / M["m00"]) else: cX, cY = 0, 0 # Draw the centroid cv2.circle(image, (cX, cY), 7, (255, 255, 255), -1) # Print area and centroid area = cv2.contourArea(contour) print(f'Contour Area: {area}, Centroid: ({cX}, {cY})') cv2.imshow('Centroids', image) cv2.waitKey(0) cv2.destroyAllWindows()
The above code computes the centroid using image moments and the area of each detected contour. Moments are particularly useful for understanding properties of shapes beyond simple outline visualization.
Let’s explore Hu moments, which are particularly useful in shape recognition. Hu moments represent shape descriptors invariant to translation, rotation, and scale.
for contour in contours: huMoments = cv2.HuMoments(M).flatten() print(f'Hu Moments: {huMoments}')
In this snippet, we calculate the Hu moments for each contour and can use these descriptors for further comparisons or classification of shapes.
Template matching helps to locate a template image within a larger image based on the shape and provide a simple method for matching.
# Load the template image template = cv2.imread('template.png', 0) w, h = template.shape[::-1] # Perform template matching res = cv2.matchTemplate(gray, template, cv2.TM_CCOEFF_NORMED) threshold = 0.8 loc = np.where(res >= threshold) # Draw rectangles around matched areas for pt in zip(*loc[::-1]): cv2.rectangle(image, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2) cv2.imshow('Template Matching', image) cv2.waitKey(0) cv2.destroyAllWindows()
This example demonstrates how to use template matching to find specific shapes within an image. A rectangle is drawn to highlight where the template has matched.
Shape analysis with OpenCV using Python opens a world of possibilities in computer vision applications. Understanding contours, moments, and shape descriptors can significantly enhance the capability of your projects, making them smarter and more efficient. Whether you’re working on a robotics project, an art generator, or any image analysis project, mastering these concepts will take you further in the domain of computer vision.
22/11/2024 | Python
05/11/2024 | Python
21/09/2024 | Python
14/11/2024 | Python
08/12/2024 | Python
22/11/2024 | Python
06/12/2024 | Python
06/12/2024 | Python
08/11/2024 | Python
08/11/2024 | Python
25/09/2024 | Python
22/11/2024 | Python