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

时间:2020-07-03 21:13:47

标签: python image opencv image-processing

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

60,000张图像,每个28x28和3个rgb通道。

我该如何更改其中的第一张图像cImgsTrain[0],从白色版本变为红色版本,并且将白色像素变成更深的红色,将灰色像素变成更浅的阴影?是否有功能可以帮助解决此问题?

enter image description here

2 个答案:

答案 0 :(得分:3)

当您想以与白色/灰色以前相同的强度更改为红色时,为什么不将两个空白图像一起堆叠呢?

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

您可以使用此代码查看。应该可以。

答案 1 :(得分:2)

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

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

相关问题