You can download this code by clicking the button below.
This code is now available for download.
This function reads an image from a specified path, converts it to a grayscale image, and then applies thresholding to get a binary image. After that, it uses OpenCV's findContours function to detect contours in the image and draws them on the original image. Finally, it displays the image with contours.
Technology Stack : OpenCV, NumPy
Code Type : Image processing
Code Difficulty : Intermediate
def find_contours(image_path):
import cv2
import numpy as np
# Read the image
image = cv2.imread(image_path)
# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply thresholding to get a binary image
_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# Find contours
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Draw contours on the original image
cv2.drawContours(image, contours, -1, (0, 255, 0), 2)
# Display the image with contours
cv2.imshow('Image with Contours', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
return contours