David
David

Reputation: 1438

Changing Whiteish Pixels in Image to a Different Color

I'm working with the MNIST dataset which contains black and white images of numbers. I am trying to change the numbers (white part) from white/gray to a different color, say red, in the same degree as the white. I've converted them into an rgb image instead of grayscale using opencv and packaged them into an array like this:

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

and

cImgsTrain.shape

outputs

(60000, 28, 28, 3)

60,000 images, each one 28x28 and three channels for rgb.

How would I change the first image in there, cImgsTrain[0], to go from this white version into a red version and have the whiter pixels be a deeper red and the grayer pixels a lighter shade? Is there a function that would help with this?

enter image description here

Upvotes: 3

Views: 964

Answers (2)

Nicolas Gervais
Nicolas Gervais

Reputation: 36584

You can use your current greyscale input as the red channel, and set all the green and blue channels to zero. You can switch them around to have the number have the color blue or green.

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

Upvotes: 2

Vardan Agarwal
Vardan Agarwal

Reputation: 2181

As you want to change to red in the same intensity as the white/gray were earlier, why don't you stack two blank images along with it.

OpenCV uses BGR so I'll be using that instead of RGB but if want RGB you can change it.

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

You can use this code and see. It should work.

Upvotes: 4

Related Questions