Program 11: Write A Program To Contour An Image
Program 11: Write A Program To Contour An Image
import cv2
import numpy as np
# Find contours
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
Output:
Explanation:
In image processing and computer vision, a contour refers to a curve joining all the
continuous points (along a boundary) that have the same color or intensity. Contours are a
useful tool for shape analysis and object detection and recognition.
2. Useful for Object Detection: By detecting contours, you can easily identify and
isolate different shapes in an image, making them useful for tasks such as object
detection and image segmentation.
import cv2: This imports the OpenCV library, which is used for computer vision tasks.
Convert to Grayscale:
The loaded color image is converted to a grayscale image because contour detection
is typically performed on single-channel images.
Find Contours:
Draw Contours:
The original and the contour images are displayed in separate windows.
cv2.waitKey(0): This function waits indefinitely until a key is pressed. It keeps the
image windows open until a key event occurs.
cv2.destroyAllWindows(): This function closes all the OpenCV windows opened by
the program.
Summary
This program effectively demonstrates how to load an image, preprocess it, find contours,
and display the results using OpenCV.
Additional information
Parameters:
gray: The source grayscale image.
0: The threshold value. In this case, since we are using Otsu's method, this value is
ignored.
255: The maximum value to use with the cv2.THRESH_BINARY_INV thresholding
type. Pixels with intensity greater than the threshold value will be set to this value
(255).
cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU: Combined flags indicating the
type of thresholding to be applied.
Otsu's Binarization
Otsu's method is a global thresholding technique that automatically determines the
optimal threshold value by minimizing the intra-class variance (the variance within
the foreground and background pixel intensities). This method is particularly useful
for images with a bimodal histogram (two distinct peaks).
Return Values
ret: The threshold value used. Since Otsu's method is applied, this value is
computed automatically and returned by the function.
thresh: The resulting binary image after applying the thresholding. This is a binary
image where pixels are either 0 or 255, based on the thresholding conditions.