在查找轮廓时,您只需要调整灰度图像的阈值以包含灰色虚线路径。由于输入图像的主要部分是白色的,因此我们可以选择接近255的阈值,例如230。然后进行二值化处理以查找轮廓。
您可以使用cv2.approxPolyDP
来计算近似的多项式形状,但这并没有太大的帮助,所以这一步是可选的。
代码片段可能如下所示:
import cv2
img = cv2.imread("/Users/anmoluppal/Downloads/1tl6D.jpg")
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(img_gray, 230, 255, cv2.THRESH_BINARY_INV)
img_, contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
largest_contour_area = 0
for cnt in contours:
if (cv2.contourArea(cnt) > largest_contour_area):
largest_contour_area = cv2.contourArea(cnt)
largest_contour = cnt
epsilon = 0.001*cv2.arcLength(largest_contour,True)
approx = cv2.approxPolyDP(largest_contour,epsilon,True)
final = cv2.drawContours(img, [approx], 0, [0, 255, 0])
cv2.findContours
在 Opencv 3.1 中返回 3 个值,但在 Opencv2.7 中仅返回 2 个值。因此这是版本相关的,您需要计算最大的轮廓,因为图像中可能会形成一些小的轮廓需要被忽略。 - ZdaR