乐闻世界logo
搜索文章和话题

How to detect simple geometric shapes using OpenCV

1个答案

1

When using OpenCV for detecting simple geometric shapes, the main steps are as follows:

1. Image Preprocessing

First, image preprocessing is required to reduce noise and simplify subsequent processing steps. This typically includes:

  • Grayscale Conversion: Convert the image from color to grayscale since shape detection typically does not rely on color information.

  • Filtering: Apply filtering methods such as Gaussian blur to smooth the image, reducing noise and irrelevant details.

python
import cv2 import numpy as np # Read the image image = cv2.imread('path_to_image.jpg') # Convert to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Apply Gaussian blur blurred = cv2.GaussianBlur(gray, (5, 5), 0)

2. Edge Detection

Use edge detection algorithms such as Canny edge detection to further process the image for identifying edges in the image.

python
# Canny edge detection edged = cv2.Canny(blurred, 30, 150)

3. Finding Contours

Extract contours from the edge image using OpenCV's findContours() method.

python
# Find contours contours, _ = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

4. Shape Recognition

Identify shapes based on the geometric properties of contours. For example, determine shapes based on the number of contour points or the ratio of perimeter to area.

python
# Iterate through contours for contour in contours: # Calculate the contour perimeter peri = cv2.arcLength(contour, True) # Approximate the contour points approx = cv2.approxPolyDP(contour, 0.04 * peri, True) # Determine the shape if len(approx) == 3: shape = "Triangle" elif len(approx) == 4: # Further distinguish quadrilaterals or rectangles (x, y, w, h) = cv2.boundingRect(approx) ar = w / float(h) shape = "Square" if ar >= 0.95 and ar <= 1.05 else "Rectangle" elif len(approx) > 4: shape = "Circle" # Here, it simply assumes contours with more than 4 points are circles # Draw the result cv2.drawContours(image, [contour], -1, (0, 255, 0), 2) cv2.putText(image, shape, (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)

5. Displaying Results

Finally, display the processed image to view the detected shapes and markers.

python
# Display the image cv2.imshow("Image", image) cv2.waitKey(0) cv2.destroyAllWindows()

This process can detect and identify basic geometric shapes in the image, such as triangles, squares, rectangles, and circles. This program can be adjusted and optimized as needed to accommodate more complex or specific application scenarios.

2024年7月2日 23:22 回复

你的答案