如何用OpenCV/Python/AI模型提取二值掩码图像中四边形顶点?
二值掩码图像中提取四边形顶点的解决方案需求
需求说明
- 输入:二值分割掩码图像(示例如下)

- 目标:检测图像中所有四边形的四个顶点坐标,输出格式要求:
output object = [ ( (x11,y11), (x12,y12), (x13,y13), (x14,y14) ) , # 第一个四边形 ( (x21,y21), (x22,y22), (x23,y23), (x24,y24) ) ] # 第二个四边形
现有尝试及问题
- 尝试过边缘检测类的文档扫描方法,无法准确定位四边形的四个顶点
- 已编写如下代码,可获取角点坐标,但无法将其组合为完整的四边形:
import imutils import cv2 import numpy as np image = cv2.imread('../masks\cpu-b-model\segmentation4.png',0) cnts = cv2.findContours(image.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) c = max(cnts, key=cv2.contourArea) output = image.copy() cv2.drawContours(output, [c], -1, (0, 255, 0), 3) (x, y, w, h) = cv2.boundingRect(c) text = "original, num_pts={}".format(len(c)) # cv2.putText(output, text, (x, y - 15), cv2.FONT_HERSHEY_SIMPLEX,0.9, (0, 255, 0), 2) cv2.imshow("Original Contour", output) cv2.waitKey(0) cv2.destroyAllWindows() print(text) for eps in np.linspace(0.05, 0.1, 10): peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, eps * peri, True) print(approx) output = image.copy() cv2.drawContours(output, [approx], -1, (0, 255, 0), 3) text = "eps={:.4f}, num_pts={}".format(eps, len(approx)) cv2.putText(output, text, (x, y - 15), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2) print("[INFO] {}".format(text)) cv2.imshow("Approximated Contour", output) cv2.waitKey(0) cv2.destroyAllWindows()
求助内容
需要可行的解决方案,使用OpenCV/Python或AI/ML模型实现提取图像中四边形四个顶点的功能。
内容的提问来源于stack exchange,提问作者alloc7260
相关产品推荐
相关产品推荐

