How to Detect Contours in an Image in Python using OpenCV
In today’s blog, we will see how we can detect contours in an image using the cv2 module. Talking about contouring it is a very useful operation when our use case involves geological terrain images or studying weather maps, etc.
Read the full article with source code here — https://machinelearningprojects.net/detect-contours/
Let’s do it…
Step 1 — Importing required packages.
import matplotlib.pyplot as plt
Step 2 — Let’s read the image….
img = cv2.imread(‘contours.png’)
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
Here we are reading the image and just converting it from BGR to RGB.
Step 3 — Convert it to grayscale for thresholding.
gray = cv2.cvtColor(img.copy(),cv2.COLOR_BGR2GRAY)
You might be thinking that why are we converting it to Grayscale when it’s already gray. The answer is that it might look like it is gray but it is still having 3 channels (R, G, B), and as we know grayscale images have only 1 channel that’s why we need to convert it to grayscale.
Step 4 — Thresholding the image to detect contours.
ret, thresh = cv2.threshold(gray, 125, 255, 0)
For finding the contours we have to threshold the image so that it is completely converted to a binary image.
Step 5 — Let’s detect contours…
Syntax: cv2.findContours(src, contour_retrieval, contours_approximation)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
NOTE: You can read more about hierarchy here.
Step 6 — Let's draw these contours on our original image.
copy_img = img.copy()
- We will be making a copy of our original image using img.copy() to draw contours on that copy image so that our original image is preserved.
- To draw contours we use cv2.drawContours() method. The first argument represents the image source, the second argument represents the contours that should be passed as a Python list, the third argument is used as an index of Contours, and other arguments are used for color thickness.
Step 7 — Finally let’s plot the results.
titles = ['original','contours']
imgs = [img, copy_img]
for i in range (2):
Note: Here blue color depicts the contours.
Do let me know if there’s any query regarding how to detect contours by contacting me on email or LinkedIn.
For further code explanation and source code visit here — https://machinelearningprojects.net/detect-contours/
So this is all for this blog folks, thanks for reading it and I hope you are taking something with you after reading this and till the next time 👋…
Read my previous post: HOW TO PLOT COLOR CHANNELS HISTOGRAM OF AN IMAGE IN PYTHON USING OPENCV