In this Python OpenCV we are going to learn about Python OpenCV Contour Detection, so contours can be explained simply as a curve joining all the continuous points (along the boundary), having same color or intensity. The contours are a useful tool for shape analysis and object detection and recognition.
This is the complete code for this lesson.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import cv2 import numpy as np img = np.zeros((200,200), dtype=np.uint8) img[50:150, 50:150] = 255 ret, thresh = cv2.threshold(img, 127, 255, 0) contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) color = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR) img = cv2.drawContours(color, contours, -1, (255,0,0), 5) cv2.imshow("Image", img) cv2.waitKey(0) cv2.destroyAllWindows() |
First of all we are going to create an empty image with numpy.
1 |
img = np.zeros((200,200), dtype=np.uint8) |
After that we are going to create our threshold.
1 |
ret, thresh = cv2.threshold(img, 127, 255, 0) |
In here we are going to find our contours, you need to pass some parameters, the first one is the source image, the second one is the contour retrieval mode and the third one is the approximation method.
1 2 |
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) |
Also we are going to convert our color from gray to bgr.
1 |
color = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR) |
And lastly we need to draw the contours, first argument is the source image, second is the contours, third argument is the index of the contours, the fourth argument is the color and fifth argument is the thickness.
1 |
img = cv2.drawContours(color, contours, -1, (255,0,0), 5) |
Run the complete code and this is the result.