Python 如何从openCV-findContours中提取X或元组值,其中Y=39

Python 如何从openCV-findContours中提取X或元组值,其中Y=39,python,python-3.x,numpy,opencv,Python,Python 3.x,Numpy,Opencv,我在一张图片上运行了cv2.findContours 结果是3条等高线。这是findContours的输出- print (cnt) [array([[[149, 0]], [[149, 1]], [[148, 2]], [[148, 8]], [[149, 9]], [[149, 11]], [[148, 12]], [[148, 39]], [[213,

我在一张图片上运行了
cv2.findContours

结果是3条等高线。这是findContours的输出-

print (cnt)
[array([[[149,   0]],
       [[149,   1]],
       [[148,   2]],
       [[148,   8]],
       [[149,   9]],
       [[149,  11]],
       [[148,  12]],
       [[148,  39]],
       [[213,  39]],
       [[213,  30]],
       [[212,  29]],
       [[213,  28]],
       [[213,  23]],
       [[212,  22]],
       [[212,   3]],
       [[211,   2]],
       [[211,   0]],
       [[161,   0]],
       [[160,   1]],
       [[159,   0]]], dtype=int32), 

array([[[148,   5]],
       [[149,   4]],
       [[150,   5]],
       [[150,   8]],
       [[149,   9]],
       [[148,   8]]], dtype=int32), 
array([[[ 0,  0]],
       [[ 0, 39]]], dtype=int32)]
我想从第一个轮廓[0]获取元组,其中
y=39
在这种情况下,我希望得到:

[[148,  39]],
[[213,  39]]

您可以使用列表理解来过滤容器中的元素

在您的示例中,数据结构有点复杂:

selection = [i for i in cnt[0] if i[0][1] == 39]
我们在cnt[0]上迭代,因为它描述了第一个轮廓。在这种情况下,我们需要一个额外的索引操作(
i[0][1]
而不是
i[1]
,因为额外的数组换行)来获取y值

我们也可以使用此操作一次性简化输出:

selection = [i[0] for i in cnt[0] if i[0][1] == 39]

OpenCV轮廓阵列可能很难使用。在与他们合作之前,我通常会这样做:

contour=np.数组([list(pt[0])用于轮廓中的ctr,用于轮廓中的pt,用于ctr中的pt])
然后您可以获得您的积分列表:

pts=等高线[np.where(等高线[:,1]==49)]

回答得很好!请注意,第一条线将所有轮廓挤压在一起。只是指出它以避免任何混淆。