Converting a wrapped NumPy array to a CvMat type in Python using cv.fromarray

I have a problem where some numpy arrays are not converted to cvMat using cv.fromarray (). The problem seems to occur whenever the numpy array is moved.

import numpy as np
import cv

# This works fine:
b = np.arange(6).reshape(2,3).astype('float32')
B = cv.fromarray(b)
print(cv.GetSize(B))

# But this produces an error:
a = np.arange(6).reshape(3,2).astype('float32')
b = a.T
B = cv.fromarray(b)
print(cv.GetSize(B))

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test_err.py", line 17, in <module>
    B = cv.fromarray(b)
TypeError: cv.fromarray array can only accept arrays with contiguous data

      

Any suggestions? Many of my arrays have been migrated at some point, so the error often occurs.

I am using Python2.7 on MacOS X Lion with NumPy 1.6.2 and OpenCV 2.4.2.1 installed from MacPorts.

+3


source to share


1 answer


You can check your arrays with an attribute flags.contiguous

, and if not, force them to use copy()

:

>>> a = np.arange(16).reshape(4,4)
>>> a.flags.contiguous
True
>>> b = a.T
>>> b.flags.contiguous
False
>>> b = b.copy()
>>> b.flags.contiguous
True

      



When you ask for a transpose, numpy doesn't actually carry the data, just the steps used to access it, unless you specifically start the copy with copy()

.

+7


source







All Articles