python - 为什么数据类型在 Opencv python 包装器中必须是 'uint8'?

标签 python opencv

我想使用以下代码创建一个灰色 颜色的图像:

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/

相关文章:

python - 如何打印最长的单词及其长度?

java - Opencv调整矩形大小同时保持质心

android - ANDROID OpenCV 中的模式识别算法 SURF、SIFT 出现异常

opencv - 如何获得使用 OpenCV 创建的窗口位置 (x,y)?

python - 来自序列化程序的自定义字段的 Django Rest Order?

python - 比较:Pycharm 与 WingIDE

python - 终端中的 Pyspark 命令启动 Jupyter notebook

python - BeautifulSoup' 没有属性 'HTML_ENTITIES

python - 提取关键帧 | python | OpenCV

c++ - 如何使用 dart :ffi 将 Uint8List 转换为 C 等效数据类型