gpt4 book ai didi

python - Python中的OpenCV putText-数组操作后发生错误

转载 作者:行者123 更新时间:2023-12-02 16:56:07 25 4
gpt4 key购买 nike

简短

我想将文字写入图像。但是,我无法理解以下行为:

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进行测试时,它们的形状相同,当我将它们与 img==img_from_container进行比较时,我得到的都是正确的。

显然我缺少了一些东西。对于这两个变量在其他方面的不同之处,我将不胜感激!

最佳答案

更改以下行即可解决问题

img_from_container = img_container[:,:,:,0].copy()
np.copy()可以清楚地制作出另一个数据副本,然后opencv可以写入该数组。先前的代码从更高维度的numpy数组获取 View ,其中 putText()未能修改。

关于python - Python中的OpenCV putText-数组操作后发生错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36042508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com