Ask Your Question
0

Initialize numpy array (cv2 python) and PerspectiveTransform

asked 2013-03-15 14:45:55 -0600

matt.hammer gravatar image

I am trying to convert some of my C++ OpenCV code to Python, and have hit a stumbling block.

I am trying to get a numpy array into the PerspectiveTransform function and have hit the following assert in the underlying C++ code (matmul.cpp, ln 1926):

CV_Assert( scn + 1 == m.cols && (depth == CV_32F || depth == CV_64F));

Now this is telling me that, first, the number of columns in the transformation matrix should be one more than the number of channels in the input matrix, and, second, that the source matrix should be made of floating point elements, right?

Here's the code that is causing the exception:

rotMat = buildRotMat(roll, pitch, yaw)
corners = np.ones((1,1,2), np.float32)
newCorners = np.zeros((1,1,2), np.float32)
cv2.perspectiveTransform(corners, newCorners, rotMat)

and from a separate function:

rotMat = np.array(
[[math.cos(alpha)*math.cos(beta),
math.cos(alpha)*math.sin(beta)*math.sin(gamma)-math.sin(alpha)*math.cos(gamma),
math.cos(alpha)*math.sin(beta)*math.cos(gamma)+math.sin(alpha)*math.sin(gamma)],
[math.sin(alpha)*math.cos(beta),
math.sin(alpha)*math.sin(beta)*math.sin(gamma)+math.cos(alpha)*math.cos(gamma),
math.sin(alpha)*math.sin(beta)*math.cos(gamma)-math.cos(alpha)*math.sin(gamma)],
[-math.sin(beta),
math.cos(beta)*math.sin(gamma),
math.cos(beta)*math.cos(gamma)]], dtype=float32)

My guess would be that I've made a numpy error (when trying to initialize a 2-channel floating point array), since I'm learning Python as I go, and this code did work fine in C++. Any help or insight would be greatly appreciated.

Thanks, Matt

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
1

answered 2013-03-15 16:15:16 -0600

matt.hammer gravatar image

After much trial & error, I figured it out. I didn't notice that the new python cv2 module reverses the order of the output and transformation matrix arguments. (different from c++ AND old python cv module). Also, it returns the output matrix, so I can (optionally) omit the output argument and return directly into a new variable:

corners = np.ones((1,1,2))
newCorners = cv2.perspectiveTransform(corners, rotMat)
edit flag offensive delete link more

Comments

that's already the second time today, that someone reports an error like this, swapped args in cv / cv2 interface

berak gravatar imageberak ( 2013-03-15 16:20:10 -0600 )edit

since i'm starting to explore the wonderful world of python too, this is my bread & butter thing:

<code>

>>> cv2.perspectiveTransform.__doc__

'perspectiveTransform(src, m[, dst]) -> dst'

</code>

berak gravatar imageberak ( 2013-03-15 16:28:31 -0600 )edit

Question Tools

Stats

Asked: 2013-03-15 14:45:55 -0600

Seen: 4,132 times

Last updated: Mar 15 '13