提高网站收录,软件开发流程八个步骤模板,山西省建设厅网站,连云港网站制作公司口碑好需求背景
基于numpy和opencv生成一个随机噪声灰度图像#xff0c;像素值是范围[0, 256)内的整数#xff0c;图像形状为(512, 512)#xff0c;并显示图像#xff0c;源码如下
import numpy as np
import cv2img np.random.randint(0, 256, size[512, 512])
cv2.imshow(像素值是范围[0, 256)内的整数图像形状为(512, 512)并显示图像源码如下
import numpy as np
import cv2img np.random.randint(0, 256, size[512, 512])
cv2.imshow(noise img, img)
cv2.waitKey(0)
cv2.destroyAllWindows()运行代码后出现以下Bug
cv2.error: OpenCV(4.8.1) D:/a/opencv-python/opencv-python/opencv/modules/highgui/src/precomp.hpp:155: error: (-215:Assertion failed) src_depth ! CV_16F src_depth ! CV_32S in function ‘convertToShow’
完整Bug截图
报错原因分析及解决方法
由np.random.randint()函数生成的numpy数组其元素默认的数据类型是32位整数(int32)而cv2.imshow函数要求输入数组数据类型是无符号8位整数(uint8)。因此将数组数据类型从int32更改为uint8即可。
错误的解决方案
# before
img np.random.randint(0, 256, size[512, 512]) # 默认是int32# after
img np.random.randint(0, 256, size[512, 512])
img.dtype np.uint8 # 直接将img对象的数据类型属性(int32)转成uint8 相当于原本32位的1个数据 变为 8位的4个数据可行的方案1
# before
img np.random.randint(0, 256, size[512, 512])# after
img np.random.randint(0, 256, size[512, 512], dtypenp.uint8) # 利用randint函数的dtype参数 提前指定好 正确的数据类型可行的方案2
# before
img np.random.randint(0, 256, size[512, 512])# after
img np.random.randint(0, 256, size[512, 512])
img np.array(img, dtypenp.uint8) # 利用np.array函数 重构 数据可行的方案3
# before
img np.random.randint(0, 256, size[512, 512])# after
img np.random.randint(0, 256, size[512, 512])
img img.astype(np.uint8) # 利用img对象的 astype方法 改变所有数据元素的数据类型