You can download this code by clicking the button below.
This code is now available for download.
This function finds contours in an image using OpenCV. It first converts the image to grayscale, applies Gaussian blur and thresholding to binarize the image, and then uses the findContours function to retrieve contours with chain approximation to reduce the number of contour points.
Technology Stack : OpenCV
Code Type : Image processing
Code Difficulty : Intermediate
def find_contours(image, mode='default', method='MORPH_EXTERNAL'):
"""
This function finds contours in an image using OpenCV.
Parameters:
image (numpy.ndarray): The input image.
mode (str): The contour retrieval mode.
method (str): The method to use for contour approximation.
Returns:
list: A list of contours.
"""
import cv2
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
_, thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
return contours