gpt4 book ai didi

python - 如何将 mnist 数据转换为 RGB 格式?

转载 作者:行者123 更新时间:2023-12-03 16:38:05 26 4
gpt4 key购买 nike

我正在尝试将 MNIST 数据集转换为 RGB 格式,每个图像的实际形状是 (28, 28),但我需要 (28, 28, 3)。

import numpy as np
import tensorflow as tf

mnist = tf.keras.datasets.mnist
(x_train, _), (x_test, _) = mnist.load_data()

X = np.concatenate([x_train, x_test])
X = X / 127.5 - 1

X.reshape((70000, 28, 28, 1))

tf.image.grayscale_to_rgb(
X,
name=None
)

但我收到以下错误:
ValueError: Dimension 1 in both shapes must be equal, but are 84 and 3. Shapes are [28,84] and [28,3].

最佳答案

您应该将 reshape 后的 3D [28x28x1] 图像存储在一个数组中:

X = X.reshape((70000, 28, 28, 1))

转换时,设置另一个数组为 tf.image.grayscale_to_rgb()的返回值功能 :
X3 = tf.image.grayscale_to_rgb(
X,
name=None
)

最后,用 matplotlib 从生成的张量图像中绘制一个示例和 tf.session() :
import matplotlib.pyplot as plt

with tf.Session() as sess:
sess.run(tf.global_variables_initializer())

image_to_plot = sess.run(image)
plt.figure()
plt.imshow(image_to_plot)
plt.grid(False)

完整代码:

import numpy as np
import tensorflow as tf

mnist = tf.keras.datasets.mnist
(x_train, _), (x_test, _) = mnist.load_data()

X = np.concatenate([x_train, x_test])
X = X / 127.5 - 1

# Set reshaped array to X
X = X.reshape((70000, 28, 28, 1))

# Convert images and store them in X3
X3 = tf.image.grayscale_to_rgb(
X,
name=None
)

# Get one image from the 3D image array to var. image
image = X3[0,:,:,:]

# Plot it out with matplotlib.pyplot
import matplotlib.pyplot as plt

with tf.Session() as sess:
sess.run(tf.global_variables_initializer())

image_to_plot = sess.run(image)
plt.figure()
plt.imshow(image_to_plot)
plt.grid(False)

关于python - 如何将 mnist 数据转换为 RGB 格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58778867/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com