Skip to content
Advertisement

Why does saving an image with OpenCV result in a black image?

So, I want to create a 500×500 white image using python Numpy library, though I can easily do it in photoshop. The code below is valid and the image is white (because I saved the image using cv2.imsave function and later I opened it with windows photos viewer). But when I try to display it using the cv2.imshow function a black image is displayed. Why is that? Is it a drawback of 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)

Advertisement

Answer

Note that the cv2 module is a thin wrapper around the C++ OpenCV package. Here’s the documentation for it, and the signature doesn’t change for the python wrapper functions that interface them. From the documentation

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

By default, numpy arrays are initialised to np.int32 or np.int64 type (it depends on your machine). If you want your arrays displayed without any change, you should ensure that you pass them as 8-bit unsigned. In your case, like this –

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

Alternatively, when initialising your arrays, do so as –

img = np.arange(..., dtype=np.uint8)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement