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

3 投票
1 回答
2914 浏览
提问于 2025-04-17 14:51

我遇到了一个问题,就是有些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

有什么建议吗?我的很多数组在某个时候都被转置过,所以这个错误经常出现。

我在MacOS X Lion上使用Python2.7,安装的NumPy版本是1.6.2,OpenCV版本是2.4.2.1,都是通过MacPorts安装的。

1 个回答

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

当你请求转置的时候,numpy 实际上并没有真正转置数据,只是改变了访问数据的方式,除非你特别使用 copy() 来触发复制。

撰写回答