15、OpenCV Python 轮廓发现
1 __author__ = "WSX" 2 import cv2 as cv 3 import numpy as np 4 # 基于拓扑结构来发现和绘制(边缘提取) 5 # cv.findContours() 发现轮廓 6 # cv.drawContours() 绘制轮廓 7 # 使用梯度 ,不需要阈值了就 8 9 def edge_demo(image): 10 blurred = cv.GaussianBlur(image, (3, 3), 0) 11 gray = cv.cvtColor(blurred, cv.COLOR_BGR2GRAY) 12 # X Gradient 13 xgrad = cv.Sobel(gray, cv.CV_16SC1, 1, 0) 14 # Y Gradient 15 ygrad = cv.Sobel(gray, cv.CV_16SC1, 0, 1) 16 #edge 17 #edge_output = cv.Canny(xgrad, ygrad, 50, 150) 18 edge_output = cv.Canny(gray, 30, 100) 19 cv.imshow("Canny Edge", edge_output) 20 return edge_output 21 22 23 def contours_demo(image): 24 """dst = cv.GaussianBlur(image, (3, 3), 0) 25 gray = cv.cvtColor(dst, cv.COLOR_BGR2GRAY) 26 ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU) 27 cv.imshow("binary image", binary)""" 28 binary = edge_demo(image) 29 30 cloneImage, contours, heriachy = cv.findContours(binary, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) 31 # cv.RETR_EXTERNAL最大轮廓 CHAIN_APPROX_SIMPLE简单的 32 #contours 放轮廓 heriachy层次信息 33 for i, contour in enumerate(contours): 34 cv.drawContours(image, contours, i, (0, 0, 255), 2) 35 #绘制(0, 0, 255)颜色 2 为宽度 若为-1 则填充轮廓 36 approxCurve = cv.approxPolyDP(contour, 4, True) 37 if approxCurve.shape[0] > 6: 38 cv.drawContours(image, contours, i, (0, 255, 255), 2) 39 if approxCurve.shape[0] == 4: 40 cv.drawContours(image, contours, i, (255, 255, 0), 2) 41 print(approxCurve.shape[0]) 42 print(i) 43 cv.imshow("detect contours", image) 44 45 def main(): 46 img = cv.imread("1.JPG") 47 cv.namedWindow("Show", cv.WINDOW_AUTOSIZE) 48 cv.imshow("Show", img) 49 50 contours_demo(img) 51 cv.waitKey(0) 52 cv.destroyAllWindows() 53 54 main()