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

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


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)