在两个给定点之间画线(OpenCV,Python)

Blu*_*ack 7 python opencv point lines

我现在在这个问题上挣扎了一个小时......

我有一个里面有一个矩形的图像:

矩形

这是我为寻找角点而编写的代码:

import cv2
import numpy as np


img = cv2.imread('rect.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = np.float32(gray)

points = cv2.goodFeaturesToTrack(gray, 100, 0.01, 10)
points = np.int0(points)

for point in points:
    x, y = point.ravel()
    cv2.circle(img, (x, y), 3, (0, 255, 0), -1)

print(points[0])
print(points[1])
print(points[2])
print(points[3])

cv2.imshow('img', img)
cv2.waitKey(0)
cv2.imwrite('rect.png', img)
Run Code Online (Sandbox Code Playgroud)

这是结果:

第一个

如您所见,它运行完美。我想要的是沿着上/下点(x1,x2 - x3,x4)画一条线。

我从现在开始生产的是这个......

cv2.line(img, (points[0]), (points[1]), (0, 255, 0), thickness=3, lineType=8)

cv2.imshow('img', img)
cv2.waitKey(0)
Run Code Online (Sandbox Code Playgroud)

但它不起作用。

任何的想法 ?

结果应该是这样的:

出去

两条线必须通过点的坐标。print(points[0])上面给出了下一个输出,例如:

[[561 168]]
[[155 168]]
[[561  53]]
[[155  53]] 
Run Code Online (Sandbox Code Playgroud)

谢谢

Kin*_*t 金 5

points = cv2.goodFeaturesToTrack(gray, 100, 0.01, 10)
points = np.int0(points).reshape(-1,2)

for point in points:
    x, y = point.ravel()
    cv2.circle(img, (x, y), 3, (0, 255, 0), -1)


y1 = min(points[:,1])
y2 = max(points[:,1])

## small and big enough 
cv2.line(img, (0, y1), (1000, y1), (0, 255, 0), thickness=3, lineType=8)
cv2.line(img, (0, y2), (1000, y2), (0, 255, 0), thickness=3, lineType=8)
Run Code Online (Sandbox Code Playgroud)


api*_*i55 5

所以首先,让我们看看你的打印,它说 points[0] 是

[[561 168]]
Run Code Online (Sandbox Code Playgroud)

但是opencv点就像

(561, 168)
Run Code Online (Sandbox Code Playgroud)

你可以像用圆一样解压它,然后做元组

x, y = points[0].ravel()
(x,y)
Run Code Online (Sandbox Code Playgroud)

或者你可以使用

tuple(points[0].ravel())
Run Code Online (Sandbox Code Playgroud)

或者

tuple(points[0][0])
Run Code Online (Sandbox Code Playgroud)

编辑

您想要从屏幕的一侧到另一侧,这也很容易。您需要做的是将一个点的 x 值更改为 0,将另一点的列值更改为 0。我认为最简单的方法是这样做:

y = points[0].ravel()[1]
cv2.line(img, (0, y), (img.shape[1], y), (0, 255, 0), thickness=3, lineType=8)
Run Code Online (Sandbox Code Playgroud)

这里要注意两点:

  1. 正如你所看到的,我并不关心第二点,因为我假设它会在同一条水平线上,如果不是,它会变得更复杂,但并不难。

  2. img.shape 返回带有图像细节的元组(行、列、通道),因为我们需要列 [1]。