目前,我正在进行一个项目,尝试使用OpenCV (Python或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)这给了我一个不准确的结果:

使用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
另一种解决办法是找到交叉口的坐标。欢迎提供任何有关此方法的线索:)
有人能给我一个如何解决这个问题的提示吗?
发布于 2017-05-12 13:21:56
求交并不是看上去那么简单,但在找到交点之前,应该考虑以下问题:
cv2.HoughLines将为每一行返回一个值为rho和theta的数组。现在,这个问题成了成对的所有行的方程组:

def intersections(edged):
# Height and width of a photo with a contour obtained by Canny
h, w = edged.shape
hl = cv2.HoughLines(edged,2,np.pi/180,190)[0]
# Number of lines. If n!=4, the parameters should be tuned
n = hl.shape[0]
# Matrix with the values of cos(theta) and sin(theta) for each line
T = np.zeros((n,2),dtype=np.float32)
# Vector with values of rho
R = np.zeros((n),dtype=np.float32)
T[:,0] = np.cos(hl[:,1])
T[:,1] = np.sin(hl[:,1])
R = hl[:,0]
# Number of combinations of all lines
c = n*(n-1)/2
# Matrix with the obtained intersections (x, y)
XY = np.zeros((c,2))
# Finding intersections between all lines
for i in range(n):
for j in range(i+1, n):
XY[i+j-1, :] = np.linalg.inv(T[[i,j],:]).dot(R[[i,j]])
# filtering out the coordinates outside the photo
XY = XY[(XY[:,0] > 0) & (XY[:,0] <= w) & (XY[:,1] > 0) & (XY[:,1] <= h)]
# XY = order_points(XY) # obtained points should be sorted
return XY结果如下:

发布于 2017-03-08 02:21:12
可以:
但是,Hough变换几乎做了同样的事情。有什么特别的理由不使用它吗?
直线的交点很容易计算。高中坐标几何课可以为你提供算法.
https://stackoverflow.com/questions/42660184
复制相似问题