TypeError: Expected Ptr<cv::UMat> for argument ‘img‘

我创建了一个numpy矩阵并使用轴对换来对多个维度进行变换,然后在上面画圆:

import cv2
import numpy as np
image = np.zeros((3, 255,255),dtype=np.uint8)
image = image.transpose((1,2,0))
cv2.circle(image, (150,150), 1, (0, 0, 255), 4)
cv2.imshow("1", image)
cv2.waitKey()

发现会有报错,在windows跟linux下的报错分别是:

#windows
TypeError: Expected Ptr for argument 'img' 

#linux
TypeError: Layout of the output array img is incompatible with cv::Mat (step[ndims-1] != elemsize or step[1] != elemsize*nchannels)

这是因为不规则的slice操作会改变连续性,如果直接创建一个(255,255,3)的矩阵在上面画圆,则其内存是连续的,并不会报错。但使用了transpose函数后,image的内存便不是连续的,因此会报错。解决方法是在transpose函数前加个ascontiguousarray函数保证其内存是连续的。

image = np.ascontiguousarray(image.transpose((1,2,0)))

你可能感兴趣的:(python,opencv)