why does cv2.imwrite method write a black square for a mnist test image dataset?

Question:

I am trying to .imwrite one of the MNIST test images with openCV but it shows just a black square. I don’t get why!!

import keras
import numpy as np
import mnist
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.utils import to_categorical
import cv2

train_images = mnist.train_images()
train_labels = mnist.train_labels()
test_images = mnist.test_images()
test_labels = mnist.test_labels()

# Normalize the images.
train_images = (train_images / 255) - 0.5
test_images = (test_images / 255) - 0.5
print(train_images.shape)
#print(test_images.shape)
img = cv2.imwrite( "img.jpg", test_images[0])
Asked By: dreamer1375

||

Answers:

As pointed out in the comments by others, you are trying to save a normalized image in the domain [-0.5, 0.5] which previously was in the domain [0, 255]. cv2.imwrite does not support this. Here’s the official help:

The function imwrite saves the image to the specified file. The image
format is chosen based on the filename extension (see imread() for the
list of extensions). Only 8-bit (or 16-bit unsigned (CV_16U) in case
of PNG, JPEG 2000, and TIFF) single-channel or 3-channel (with ‘BGR’
channel order) images can be saved using this function

Save your image before normalization or undo it like this:

img = cv2.imwrite( "img.jpg", (test_images[0] + 0.5) * 255)

Answered By: paulgavrikov

The idea is right, but the correction is not:

img = cv2.imwrite('img.jpg', (test_images[0] * 255 + 0.5).astype('int'))
Answered By: Claudio Sevlacc
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.