In this Python OpenCV iam going to talk about creating Contour Detection Example. first of all let’s talk about Contour.
Python OpenCV Tutorial: Creating a Contour Detection Example
Contours can be explained simply as a curve joining all the continuous points (along the boundary), having same color or intensity. The contours are a useful tool for shape analysis and object detection and recognition.
What is Contour Detection?
Contour detection is a fundamental concept in computer vision and image processing. It is used for identifying and extracting the boundaries of objects inside an image. A contour, in this context is a curve that joins continuous points along the boundary of an object with the same color or intensity.
Some Key Features of Contour Detection
- Object Boundaries: Contours are used to outline the boundaries of objects inside an image. These boundaries represent the areas where there is a significant change in pixel intensity or color.
- Curve Representation: Contours are often represented as curves, typically in the form of a sequence of (x, y) coordinates that describe the contour’s path.
- Useful in Shape Analysis: Contours are useful for shape analysis in computer vision. They provide information about the size, shape and spatial distribution of objects inside an image.
- Usage: Contour detection has different usages, including object recognition, shape recognition, image segmentation and object tracking.
- Detection Techniques: Contour detection algorithms may be different in complexity and approach. Common techniques include thresholding, edge detection (such as Sobel or Canny edge detection), gradient-based methods and mathematical morphology operations.
Python OpenCV Contour Detection Example Code
So now this is the complete code for Python OpenCV Contour Detection Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import cv2 import numpy as np # Create 200x200 black image img = np.zeros((200, 200), dtype=np.uint8) # Create white square in the center of the image img[50:150, 50:150] = 255 # Apply binary threshold to the image # All pixel values greater than 127 are set to 255 (white) ret, thresh = cv2.threshold(img, 127, 255, 0) # Find contours in the thresholded image # RETR_TREE retrieves all the contours # CHAIN_APPROX_SIMPLE compresses horizontal, vertical, and diagonal segments contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Convert grayscale image to a BGR image color = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) # Draw contours on the BGR image # -1 means drawing all contours, # (0, 255, 0) is the color (green), # and 2 is the thickness of the contour lines img = cv2.drawContours(color, contours, -1, (0, 255, 0), 2) # Display the image with contours cv2.imshow("contours", color) # Wait indefinitely until a key is pressed cv2.waitKey() # Destroy all OpenCV windows cv2.destroyAllWindows() |
OK in the above code first we have created a blank image, also we have placed a white square in the image
1 2 |
img = np.zeros((200, 200), dtype=np.uint8) img[50:150, 50:150] = 255 |
Also before finding contours, apply threshold or canny edge detection.
1 |
ret,thresh = cv2.threshold(img, 127, 255, 0) |
So now we are going to create contours, this function has 3 parameters, input image, hierarchy type, and the contour approximation method.
1 |
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) |
cv2.RETR_TREE will retrieve the entire hierarchy of contours in the image, enabling you to establish “relationships” between contours. If you only want to retrieve the most external contours, use cv2.RETR_EXTERNAL. This is particularly useful when you want to eliminate contours that are entirely contained in other contours (for example,vast majority of cases, you won’t need to detect an object within another object of the same type).
Also this line of code is for drawing contours
1 |
img = cv2.drawContours(color, contours, -1, (0, 255, 0), 2) |
Run the complete code and this will be the result
FAQs:
How to detect contours in OpenCV?
To detect contours in OpenCV, you can follow these steps:
- Preprocess the Image: Convert the image to grayscale and apply any necessary preprocessing, such as smoothing or thresholding.
- Find Contours: Use cv2.findContours() function to find contours in the preprocessed image. This function returns a list of contours detected in the image.
- Draw Contours: Optionally, you can draw the detected contours on a copy of the original image using cv2.drawContours() function.
How to find contour area in OpenCV Python?
For finding contour area in OpenCV Python, you can use cv2.contourArea() function. This is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import cv2 # Read the image image = cv2.imread("lena.tif") # Convert image to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Find contours contours, _ = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Iterate through contours calculate area for contour in contours: area = cv2.contourArea(contour) print("Contour Area:", area) |
What is cv2.CHAIN_APPROX_SIMPLE?
In OpenCV Python, cv2.CHAIN_APPROX_SIMPLE is a flag, and it is used in contour detection algorithms. It specifies the contour approximation method to compress the contours segments while retaining essential information.
Subscribe and Get Free Video Courses & Articles in your Email