4

I'm new to python and I don't know how to create numpy array that may be used in opencv functions. I've got two vectors defined as follows:

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

and the result is:

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

I want to create opencv contour to be used in ex. cv2.contourArea(contour). I read Checking contour area in opencv using python but cannot write my contour numpy array properly. What's the best way to do that?

1
  • 1
    It looks like cv2 contours are 3-dimensional numpy arrays. If you test out contour.shape you'll be able to work out it's dimensions. If you want to write a compatible numpy array it will need to have 3 dimensions. For example numpy.zeros(1,2,3) will create a 3D array of zeros of shape 1x2x3... Try testing that out! Commented Jul 27, 2016 at 10:09

1 Answer 1

2

Here's some example code, that first checks the dimensions of a contour calculated from a test image, and makes a test array and has success with that as well. I hope this help you!

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer! It is very usefull, altough my problem is that my input is not an image but contour points of a structure read from the file. Based on that i create binary image where contour points are ones, and background is 0. Applying cv2.findContours on that binary image results in finding many contours, but i know that there only should be one. That's why i wanted to artificially create the contour from the points, but i don't know how to put them into the structure like this: contour = np.array([[[0,0]], [[10,0]], [[10,10]], [[5,4]]])
this does not answer the question. this finds contours from an image.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.