Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to transform a OpenCV cvMat back to ndarray in numpy ?

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.

like image 742
PinkyJie Avatar asked Apr 23 '11 05:04

PinkyJie


People also ask

Does OpenCV return NumPy array?

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.

Can an image could be converted into a NumPy array?

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.

Is Ndarray same as NumPy array?

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.


2 Answers

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)
like image 64
rroowwllaanndd Avatar answered Sep 18 '22 02:09

rroowwllaanndd


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.]])
like image 44
joaquin Avatar answered Sep 20 '22 02:09

joaquin