为什么使用OpenCV保存图像会导致黑色图像?

5

我想使用Python Numpy库创建一个500x500的白色图像,尽管我可以很容易地在Photoshop中完成。下面的代码是有效的,而且图像是白色的(因为我使用了cv2.imsave函数保存图像,稍后我用Windows照片查看器打开它)。但是,当我尝试使用cv2.imshow函数显示它时,会显示一个黑色图像。这是为什么呢?是cv2的缺点吗?

import cv2
import numpy as np

img = np.arange(500*500*3)
for i in range(500*500*3):
    img[i] = 255
img = img.reshape((500, 500, 3))
cv2.imwrite("fff.jpg", img)
cv2.imshow('', img)

2
你可能需要显示int8数据类型的数组 - img.astype(np.uint8) - cs95
你懂的,我修改了第三行并添加了参数"dtype=np.uint8",然后它就可以工作了。这很难找到,我花了几个小时才找到它。 - user8193156
我可以想象这是一个经常出现的问题,所以我找到了文档,并在答案中链接了它。 - cs95
1个回答

4
请注意,cv2模块是C++ OpenCV包的轻量级封装。这是它的文档,Python封装函数与其交互的签名不会改变。从文档中 -
void cv::imshow   (const String &winname,
       InputArray     mat 
 )        

Displays an image in the specified window.

The function imshow displays an image in the specified window. [...]

  • 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].

默认情况下,numpy数组被初始化为np.int32np.int64类型(这取决于您的计算机)。如果您希望您的数组显示时不发生任何更改,应确保将它们传递为8位无符号。在您的情况下,如下所示 -

cv2.imshow('', img.astype(np.uint8))

另外,当初始化数组时,可以这样做 -

img = np.arange(..., dtype=np.uint8)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接