加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 11:25:25 所属栏目:Python 来源:网络整理
导读:我有一个问题,其中一些numpy数组不使用cv.fromarray()转换为cvMat.只要numpy数组被转置,就会出现问题. import numpy as npimport cv# This works fine:b = np.arange(6).reshape(2,3).astype('float32')B = cv.fromarray(b)print(cv.GetSize(B))# But this p
我有一个问题,其中一些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,从MacPorts安装了NumPy 1.6.2和OpenCV 2.4.2.1.

解决方法

您可以使用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()触发副本.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读