使用cv.fromarray将转置后的NumPy数组转换为Python中的CvMat类型

Dav*_*d A 3 python opencv numpy

我有一个问题,其中一些numpy数组不使用cv.fromarray()转换为cvMat.只要numpy数组被转置,就会出现问题.

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
Run Code Online (Sandbox Code Playgroud)

有什么建议?我的许多阵列都在某些时候进行了转换,因此错误频繁出现.

我在MacOS X Lion上使用Python2.7,从MacPorts安装了NumPy 1.6.2和OpenCV 2.4.2.1.

Jai*_*ime 7

您可以使用该flags.contiguous属性检查数组,如果不是,请使用以下内容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
Run Code Online (Sandbox Code Playgroud)

当你要求转置时,numpy实际上并不转置数据,只有用于访问它的步幅,除非你专门触发副本copy().