OpenCV findContours detects change in the image color and marked it as contour.
In this example using archery target face, findContours detects the outer circle, yellow circle, bullseye circle, logos on top left and bottom left.
In this case, findContours doesn’t detect the red circle contour.
The Original Image
The Image Gray
The Find Contours Image
Green color is the contours found on the image.
The OpenCV Python Code
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 |
import os import cv2 as cv import numpy as np import matplotlib.pyplot as plt def findContours(): root = os.getcwd() imgPath = os.path.join(root, 'images/target.jpg') img = cv.imread(imgPath) #change to GRAY to easily detect the contours imgGray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) ret, thresh = cv.threshold(imgGray, 127, 255, 0) contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) imgContours = cv.drawContours(img, contours, -1, (0,255,0), 3) plt.figure() plt.subplot(121) plt.imshow(imgContours) plt.show() if __name__ == '__main__': print("Start") findContours() |
Conclusion
findContours is an easy way to automatically detect an image shape or outline.
References:
- https://docs.opencv.org/4.x/d4/d73/tutorial_py_contours_begin.html
- https://medium.com/analytics-vidhya/opencv-findcontours-detailed-guide-692ee19eeb18