SHORT
我想将文字写入图像。但是,我无法理解以下行为:
import numpy as np
import cv2
# create an image
img = np.ones((512,512,3), dtype = np.uint8)
# create an image container (I have to do this as I cycle through many folder and collect images)
img_container = np.zeros((512,512,3,5), dtype = np.uint8)
# send img to the container array
img_container[:,:,:,0] = img[:,:,:]
# I can add text to the original image
cv2.putText(img, 'Hello World', (10,500), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255),2 )
cv2.imshow('img', img)
# When I retrieve the img again..
img_from_container = img_container[:,:,:,0]
# ..I am unable to do so however
cv2.putText(img_from_container, 'Hello World', (10,500), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255),2 )
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: Layout of the output array img is incompatible with cv::Mat (step[ndims-1] != elemsize or step[1] != elemsize*nchannels)
LONG
我不明白两个变量(img和img_from_container)之间的区别,因为它们都是dtype = np.uint8
,它们在使用img.shape
进行测试时具有相同的形状,并且我将它们与{{进行比较1}}我全都是真的。
显然我错过了一些东西。关于这两个变量的不同之处,我会非常感激任何提示和建议!
答案 0 :(得分:3)
更改以下行解决了问题
img_from_container = img_container[:,:,:,0].copy()
np.copy()
清楚地表明了另一个数据副本,然后opencv能够写入该数组。前面的代码从更高维度的numpy数组中获取视图,其中putText()
无法修改。