目前我正在进行一个项目,尝试使用OpenCV(Python、Java或C++)在照片中找到矩形表面的角落。
我通过筛选颜色选择了所需的表面,然后得到了掩码并将其传递给cv2.findContours
函数:
cnts, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnt = sorted(cnts, key = cv2.contourArea, reverse = True)[0]
peri = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.02*peri, True)
if len(approx) == 4:
cv2.drawContours(mask, [approx], -1, (255, 0, 0), 2)
这给出了我一个不准确的结果:
![findContours result](https://istack.dev59.com/wdhrH.webp)
cv2.HoughLines
,我已经成功得到4条直线来精确描述表面。它们的交点正是我所需要的:edged = cv2.Canny(mask, 10, 200)
hLines = cv2.HoughLines(edged, 2, np.pi/180, 200)
lines = []
for rho,theta in hLines[0]:
a = np.cos(theta)
b = np.sin(theta)
x0 = a*rho
y0 = b*rho
x1 = int(x0 + 1000*(-b))
y1 = int(y0 + 1000*(a))
x2 = int(x0 - 1000*(-b))
y2 = int(y0 - 1000*(a))
cv2.line(mask, (x1,y1), (x2,y2), (255, 0, 0), 2)
lines.append([[x1,y1],[x2,y2]])
问题是:是否有可能调整findContours
?
另一个解决方案是找到交点的坐标。欢迎提供有关此方法的线索。
有人能给我提示如何解决这个问题吗?
cos(theta1)*X+sin(theta1)*Y-rho1=0 cos(theta2)*X+sin(theta2)*Y-rho2=0
我已经将此解决方案添加到我的问题中。 - Aray Karjauv