为什么 cv2.imwrite 方法会为 mnist 测试图像数据集写入一个黑色方块?

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

我正在尝试使用 openCV .imwrite 一张 MNIST 测试图像,但它只显示一个黑色方块。我不明白为什么!!

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

正如其他人在评论中指出的那样,您正在尝试将规范化图像保存在域 [-0.5, 0.5] 中,而该域之前位于域 [0, 255] 中。 cv2.imwrite 不支持这个。官方帮助如下:

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

在规范化之前保存图像或像这样撤消它:

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