I follow the code in OpenCV cookbook for python interface to transform cvMat to numpy array:
mat = cv.CreateMat(3,5,cv.CV_32FC1)
cv.Set(mat,7)
a = np.asarray(mat)
but with OpenCV 2.1 on my PC, it does not work. The result a here is a object array, using "print a" does not print all element in a, only print <cvmat(type=42424005 rows=3 cols=5 step=20 )>
. so how to fully transform a OpenCV Mat object to original numpy.ndarray object.
Can OpenCV read NumPy array? You can read image into a numpy array using opencv library. The array contains pixel level data. And as per the requirement, you may modify the data of the image at a pixel level by updating the array values.
Images are an easier way to represent the working model. In Machine Learning, Python uses the image data in the format of Height, Width, Channel format. i.e. Images are converted into Numpy Array in Height, Width, Channel format.
numpy. array is just a convenience function to create an ndarray ; it is not a class itself. You can also create an array using numpy. ndarray , but it is not the recommended way.
Try using appending [:,:]
to the matrix (ie. use mat[:,:]
instead of mat
) in your call to np.asarray
- doing this will also allows asarray
to work on images.
Your example:
>>> import cv
>>> import numpy as np
>>> mat = cv.CreateMat( 3 , 5 , cv.CV_32FC1 )
>>> cv.Set( mat , 7 )
>>> a = np.asarray( mat[:,:] )
>>> a
array([[ 7., 7., 7., 7., 7.],
[ 7., 7., 7., 7., 7.],
[ 7., 7., 7., 7., 7.]], dtype=float32)
And for an image:
>>> im = cv.CreateImage( ( 5 , 5 ) , 8 , 1 )
>>> cv.Set( im , 100 )
>>> im_array = np.asarray( im )
>>> im_array
array(<iplimage(nChannels=1 width=5 height=5 widthStep=8 )>, dtype=object)
>>> im_array = np.asarray( im[:,:] )
>>> im_array
array([[100, 100, 100, 100, 100],
[100, 100, 100, 100, 100],
[100, 100, 100, 100, 100],
[100, 100, 100, 100, 100],
[100, 100, 100, 100, 100]], dtype=uint8)
You are right, the cookbook example is not working either for me and I get the same output as yours (win xp, python 2.6.6, opencv 2.1., numpy 1.5.1).
Maybe you can use something similar to:
>>> mat = cv.CreateMat(3,5,cv.CV_32FC1)
>>> cv.Set(mat,7)
>>> mylist = [[mat[i,j] for i in range(3)] for j in range(5)]
>>> ar = np.array(mylist)
>>> ar
array([[ 7., 7., 7.],
[ 7., 7., 7.],
[ 7., 7., 7.],
[ 7., 7., 7.],
[ 7., 7., 7.]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With