OpenCV中的轮廓分析
代码实现:
import cv2
import numpy as np
#轮廓分析(以边数划分)
img = cv2.imread('polydp.png')
cv2.imshow('shape',img)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,binary = cv2.threshold(gray,0,255,cv2.THRESH_BINARY|cv2.THRESH_OTSU)
contours,heriachy = cv2.findContours(binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
# cv2.drawContours(img,contours,-1,(100,200,255),2)
# cv2.imshow('binary',img)
for i,contour in enumerate(contours):
polydp = cv2.approxPolyDP(contour,4,True)
#polydp.shape的第一个参数是边缘的边数(多边形)
print(polydp.shape)
if polydp.shape[0] > 10:
cv2.drawContours(img,contours,i,(255,0,0),2)
elif polydp.shape[0] > 6:
cv2.drawContours(img,contours,i,(0,255,0),2)
else:
cv2.drawContours(img,contours,i,(0,0,255),2)
cv2.imshow('measure',img)
cv2.waitKey()
运行结果: