grayscale_to_rgb conversion

Hi,

I have MNIST grayscale pixel image data of 28 by 28 pixels but I want to convert into RGB. I am struggling to find the way how to convert whole dataset to RGB.

Any kind of help would be appreciated !!

Thank you in advance!!

Just to make sure I understand your question, are you saying you want to convert a grayscale intensity (like a 28x28 matrix of numbers between 0 and 255) to the equivalent gray color on the RGB scale?

On the RGB scale, gray colors have RGB values that are all equal

library(scales)

show_col(gray(seq(0,1,0.1)))

So, for a single pixel, you could do this:

gray.level = 128

# Using RGB function
gray.rgb1 = rgb(gray.level/255, gray.level/255, gray.level/255)

# Or use the gray function to do the RGB conversion
gray.rgb2 = gray(gray.level/255)

# Either way, you get color represented by the original pixel value
grays = c(gray(gray.level/255), gray.rgb1, gray.rgb2)

show_col(grays, ncol=3)

For an image (a matrix of gray levels) you could do this:

par(mfrow=c(1,2),
    mar=c(1,1,1,1))

# Create gray-level image
set.seed(2)
img = matrix(sample(0:255, 28*28, replace=TRUE), nrow=28)
img[1:3, 1:3]
#>      [,1] [,2] [,3]
#> [1,]   84  111   47
#> [2,]  206  227   40
#> [3,]  197  170   44
plot(as.raster(img, max=255))

# Convert to equivalent RGB color
as.raster(img/255)[1:3,1:3]
#>      [,1]      [,2]      [,3]     
#> [1,] "#545454" "#6F6F6F" "#2F2F2F"
#> [2,] "#CECECE" "#E3E3E3" "#282828"
#> [3,] "#C5C5C5" "#AAAAAA" "#2C2C2C"
img.rgb = as.raster(img/255)
plot(img.rgb)

Created on 2020-10-26 by the reprex package (v0.3.0)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.