【问题标题】:why does cv2.imwrite method write a black square for a mnist test image dataset?为什么 cv2.imwrite 方法为 mnist 测试图像数据集写一个黑色方块?
【发布时间】:2020-12-02 05:28:49
【问题描述】:

我正在尝试使用 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])

【问题讨论】:

  • AttributeError: 'bool' object has no attribute 'dtype' ,但我不明白为什么!
  • imwrite() 会将 Numpy uint8/16 数组保存为 JPEG/PNG。
  • 您是否尝试过在标准化之前保存图像?我认为问题可能来自那里,因为您将像素标准化为 [-0.5, 0.5]

标签: python opencv cv2 mnist


【解决方案1】:

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

函数imwrite将图像保存到指定文件。图片 格式是根据文件扩展名选择的(参见 imread() 扩展名列表)。只有 8 位(或 16 位无符号 (CV_16U) 以防万一 PNG、JPEG 2000 和 TIFF)单通道或 3 通道(带有“BGR” 频道顺序)图像可以使用此功能保存

在标准化之前保存您的图像或像这样撤消它:

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

【讨论】:

    猜你喜欢
    • 2017-07-13
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多