我想使用以下代码创建一个灰色 颜色的图像:
import numpy as np
import cv2
cv=cv2
s=np.zeros((240, 320, 3), dtype=int)
s[s==0]=128
cv.imshow('3', s)
cv.waitKey()
cv.destroyAllWindows()
但我得到了一个完全黑色的图像。当我将图像写入文件时,它确实是一个灰色图像:
fn='example.jpg'
cv.imwrite(fn, s)
所以我必须将 int
更改为 uint8
,然后一切正常。但我仍然很好奇,为什么我必须使用 uint8
而不是 int
,是否有任何文档对此进行描述?
最佳答案
来自documentation , OpenCV 根据数组的类型改变它的行为:
- If the image is 8-bit unsigned, it is displayed as is.
- If the image is 16-bit unsigned or 32-bit integer, the pixels are divided by 256. That is, the value range [0,255*256] is mapped to [0,255].
- If the image is 32-bit floating-point, the pixel values are multiplied by 255. That is, the value range [0,1] is mapped to [0,255].
因此,以下将生成相同的图像灰度图像:
s = np.zeros((240, 320), dtype=np.uint8)
s[s==0] = 128
int32
:
s = np.zeros((240, 320), dtype=np.int32)
s[s==0] = 128 * 256
float32
:
s = np.zeros((240, 320), dtype=np.float32)
s[s==0] = 128 / 256.0
关于python - 为什么数据类型在 Opencv python 包装器中必须是 'uint8'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23749968/