将图像中的白色像素更改为其他颜色

2024-09-23 06:26:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用MNIST数据集,它包含数字的黑白图像。我正在尝试将数字(白色部分)从白色/灰色更改为与白色相同程度的不同颜色,例如红色。我使用opencv将它们转换为rgb图像,而不是灰度图像,并将它们打包成如下数组:

cImgsTrain = np.asarray([cv2.cvtColor(img.reshape(28,28),cv2.COLOR_GRAY2RGB) for img in x_train])

cImgsTrain.shape

输出

(60000, 28, 28, 3)

60000张图像,每幅28x28,三个rgb通道

我将如何更改其中的第一幅图像cImgsTrain[0],从这个白色版本变为红色版本,并使白色像素变为深红色,灰色像素变为浅色调?是否有一个功能可以帮助实现这一点

enter image description here


Tags: 数据图像版本img颜色数字rgb像素
2条回答

由于您希望以与先前的白色/灰色相同的强度更改为红色,为什么不将两个空白图像叠加在一起呢

OpenCV使用BGR,所以我将使用它而不是RGB,但如果需要RGB,您可以更改它

import numpy as np

#assuming img contains a grayscale image of size 28x28
b = np.zeros((28, 28), dtype=np.uint8)
g = np.zeros((28, 28), dtype=np.uint8)
res = cv2.merge((b, g, img))
cv2.imshow('Result', res)
cv2.waitKey(0)
cv2.destroyAllWindows()

您可以使用此代码并查看。它应该会起作用

您可以使用当前灰度输入作为红色通道,并将所有绿色和蓝色通道设置为零。您可以将其切换为蓝色或绿色

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

(x, _), (_, _) = tf.keras.datasets.mnist.load_data()

x = x[0]

f = np.concatenate([x[..., None],
                    np.zeros((28, 28, 1)).astype(int),
                    np.zeros((28, 28, 1)).astype(int)], axis=-1)
plt.imshow(f)

enter image description here

相关问题 更多 >