如图
如果用逼近的方法,不能补齐,反而会切掉。
能用什么方法补齐?
引自微信小程序:皆我百晓生:
import cv2
import numpy as np
# 读取图像
image = cv2.imread('71.png')
# 灰度图
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray, 50, 255, cv2.THRESH_BINARY)
# 查找轮廓
contours, _ = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# 最大轮廓
max_area = 0
max_contour = np.array([])
for contour in contours:
# 逼近轮廓以减少点的数量
epsilon = 0.1 * cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, epsilon, True)
# 面积
area = cv2.contourArea(approx)
if area > max_area:
max_area = area
max_contour = approx
# 补齐缺角
hull = cv2.convexHull(max_contour)
# 画轮廓
cv2.drawContours(image, [hull], 0, (0, 0, 255), 3)
# 显示结果
cv2.imshow('image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()