python+opencv contour detection code parsing

  • 2020-06-23 00:53:51
  • OfStack

First of all, you can have a preliminary understanding of OpenCV, for reference: a brief understanding of OpenCV

A contour (Contours) is a curve with the same color or density that connects all continuous points. Contour detection is very useful for shape analysis and object detection and recognition.

Before the contour detection, the image should be 2-valued or Canny edge detection. In OpenCV, the object to be looked for is white and the background must be black, so this must be guaranteed when the image is preprocessed.


import cv2 
 
# Read the pictures  
img = cv2.imread("1.png") 
 
#  It has to be converted to grayscale first  
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
 
# 2 threshold  
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINAEY) 
 
#  Looking for contour  
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) 
 
#  Draw the outline, -1, Represents all the Outlines, and the brush color is (0, 255, 0) , i.e., Green , the thickness of 3 
cv2.drawContours(img, contours, -1, (0, 255, 0), 3) 
 
#  Display images  
cv2.namedWindow("Contours", cv2.NORMAL_WINDOW) 
cv2.imshow("Contours", img) 
 
#  Waiting for keyboard input  
cv2.waitKey(0) 
cv2.destroyAllWindows() 

conclusion

This example involves some simple processing of the picture, such as picture reading, gray display, 2 value, you can refer to.

That is the end of this article on python+opencv contour detection code analysis, I hope to help you. Those who are interested can continue to see this site:

OpenCV-Python realizes profile detection example analysis

python+opencv simple face recognition code example

If there is any deficiency, please let me know. Thank you for your support!


Related articles: