输入
输出 10
import cv2
import numpy as np
path, filename = 'C:\\Users\\', 'ed.png'
img = cv2.imread(path+filename)
#预处理 转灰度图
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#阈值
ret,thresh1 = cv2.threshold(gray ,127,255,cv2.THRESH_BINARY)
# _ ,thresh1 = cv2.threshold(gray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# thresh1 = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_MEAN_C,
# cv2.THRESH_BINARY,3,0)
#寻找轮廓 按照面积排序
cnt,_ = cv2.findContours(thresh1, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnt = sorted(cnt,key=cv2.contourArea, reverse=True)[:2] # 取面积最大的两个轮廓
# 画最大的轮廓
cv2.drawContours(img, [cnt[0]], -1, (0,255,0), 3)
#用vertex来记录每个轮廓的顶点
peri = cv2.arcLength(cnt[0],True)
vertex = cv2.approxPolyDP(cnt[0],0.01 * peri,True)
print('多边形的边数:', len(vertex))
# print(len(vertex))
# print(vertex)
vertex = np.array(vertex).reshape(-1, 2)
for i in range(vertex.shape[0]):
cv2.circle(img, center=vertex[i], radius=20, color=(0,0,255), thickness=5)
cv2.namedWindow('img', cv2.WINDOW_NORMAL)
cv2.imshow('img', img)
cv2.imwrite('result.png', img)
cv2.waitKey(0)
效果