2016-07-27 15 views
3

我是python的新手,我不知道如何创建可用于opencv函数的numpy数组。 我有定义两个向量如下:创建用于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] 

我想创建OpenCV的轮廓在离被使用。 cv2.contourArea(contour)。我读Checking contour area in opencv using python,但不能正确地写我的轮廓numpy阵列。什么是最好的方式来做到这一点?

+1

它看起来像cv2等高线是三维numpy阵列。如果你测试'contour.shape',你就可以计算出它的尺寸。如果你想写一个兼容的numpy数组,它需要有3个维度。例如'numpy.zeros(1,2,3)'会创建一个形状为1x2x3的零的三维数组......尝试测试一下! – Sam

回答

0

下面是一些示例代码,它首先检查从测试图像中计算出的轮廓的尺寸,并制作一个测试数组,并取得成功。我希望这对你有所帮助!

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 
+0

感谢您的回答!这是非常有用的,尽管我的问题是我的输入不是图像,而是从文件中读取结构的轮廓点。基于此,我创建了二进制图像轮廓点是1,背景为0.在该二进制图像上应用cv2.findContours导致发现许多轮廓,但我知道应该只有一个。这就是为什么我想从这些点人为地创建轮廓,但是我不知道如何将它们放入这样的结构中:contour = np.array([[[0,0]],[[10,0] ],[[10,10]],[[5,4]]]) – Biba