【问题标题】:Create numpy array (contour) to be used with opencv functions创建要与 opencv 函数一起使用的 numpy 数组(轮廓)
【发布时间】:2016-07-27 18:16:35
【问题描述】:

我是 python 新手,我不知道如何创建可用于 opencv 函数的 numpy 数组。 我有两个向量定义如下:

X=np.array(x_list)
Y=np.array(y_list)

结果是:

[ 250.78  250.23  249.67 ...,  251.89  251.34  250.78]
[ 251.89  251.89  252.45 ...,  248.56  248.56  251.89]

我想创建用于 ex 的 opencv 轮廓。 cv2.contourArea(contour)。我阅读了Checking contour area in opencv using python,但无法正确写入我的轮廓 numpy 数组。最好的方法是什么?

【问题讨论】:

  • 看起来 cv2 轮廓是 3 维 numpy 数组。如果您测试contour.shape,您将能够计算出它的尺寸。如果你想写一个兼容的 numpy 数组,它需要有 3 个维度。例如numpy.zeros(1,2,3) 将创建一个形状为 1x2x3 的 3D 零数组...尝试测试一下!

标签: python opencv


【解决方案1】:

这里有一些示例代码,它首先检查从测试图像计算的轮廓的尺寸,然后创建一个测试数组,并且也取得了成功。希望对您有所帮助!

import cv2
import numpy as np

img = cv2.imread('output6.png',0) #read in a test image
ret,thresh = cv2.threshold(img,127,255,0)
im2,contours,hierarchy = cv2.findContours(thresh, 1, 2)

cnt = contours[0]

print cnt.shape #this contour is a 3D numpy array
print cv2.contourArea(cnt) #the function prints out the area happily

#######Below is the bit you asked about

contour = np.array([[[0,0]], [[10,0]], [[10,10]], [[5,4]]]) #make a fake array
print cv2.contourArea(contour) #also compatible with function

【讨论】:

  • 感谢您的回答!它非常有用,尽管我的问题是我的输入不是图像,而是从文件中读取的结构的轮廓点。基于此,我创建了轮廓点为 1 且背景为 0 的二进制图像。在该二进制图像上应用 cv2.findContours 会导致找到许多轮廓,但我知道应该只有一个。这就是为什么我想从点人工创建轮廓,但我不知道如何将它们放入这样的结构中:contour = np.array([[[0,0]], [[10,0] ], [[10,10]], [[5,4]]])
  • 这没有回答问题。这会从图像中找到轮廓。
猜你喜欢
  • 2016-08-11
  • 2014-11-20
  • 2013-07-11
  • 1970-01-01
  • 2023-03-21
  • 2012-12-19
  • 2014-05-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多