简体   繁体   English

使用python从opencv中的findcontours检测到的单个轮廓中提取坐标

[英]Extracting the coordinates from a single contour detected by the findcontours in opencv using python

Here my code to store (x,y) in two found by cv2.findcontours in OpenCV python. 这是我在OpenCV python中的cv2.findcontours找到的两个存储(x,y)代码。

I have selected a random contour 我选择了随机轮廓

c=contour[6]

Now I want x an y values detected in a separate array to perform some operation 现在我希望在单独的数组中检测到x和y值以执行一些操作

numpy array are stored in this fashion. numpy数组以这种方式存储。

[[[ 746  997]]
 [[ 744  998]]
 [[ 742  999]]
 [[ 740 1000]]]

I tried using this to extract x values 我试图用它来提取x值

x = c[:,[0]]

but I'm getting the same array back. 但我得到了相同的阵列。

So I try to extract using this loop 所以我尝试使用此循环提取

    for a in c:
      for b in a:
        s_x = np.append(s_x, b[0])
        s_y = np.append(s_y, b[1])

Is there a simple way to select x coordinates, than going through the loop and not having this error at all? 有没有一种简单的方法可以选择x坐标,而不是遍历循环且完全没有此错误?

看来您的数组有额外的维度,因此您可以删除它,然后建立索引。

x = c.squeeze()[:, 0]
cnt = cnts[1]             # choose one 
cnt = cnt.reshape(-1,2)   # change the shape 
xs  = cnt[:,0]            # get xs

Your array has three dimensions. 您的数组具有三个维度。 The details can be seen with the shape attribute. 可以通过shape属性看到详细信息。

import numpy as np

c = np.array([[[ 746,  997]],
              [[ 744,  998]],
              [[ 742,  999]],
              [[ 740, 1000]]])
print(c.shape)

(4,1,2) (4,1,2)

Once you have the shape, slice the array. 确定形状后,将阵列切成薄片。

x = c[:,0,0]
print(x)

[746 744 742 740] [746 744 742 740]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM