jeff6868
jeff6868

Reputation: 163

Convert RGB to hexadecimal colors from image and keep image dimensions

I want to convert colors from an 2000x2000 pixels RGB image (an array with the three separated channels), into one single channel, corresponding to the hexadecimal colors. I would like also to keep at the same time the dimensions of my image, in order to find the exact hexadecimal color of each pixel. The aim is then to find the position of all pixels containing a specific color.

Let's take this reproductible example:

    # A 3x3 pixels image 

    img <- array(runif(3,0,1), dim = c(3L, 3L, 3L))

    # The result I would expect (a unique matrix of hexadecimal values,
    # corresponding to the conversion and the merging of the RGB values)

    img_output <-matrix(c("#B1F5E1","#95E4EE","#A5EDD8","#517760",
    "#A1E2C7","#00FFFF","#A9EFDB","#A9EFC4","#73CEE6"),nrow=3,ncol=3)

    # In order then to find the position of specific color pixels in
    # my image

    which(img_output=="#95E4EE", arr.ind=TRUE)

For the moment, I already have the function for converting RGB colors to hexadecimal, but it returns me a character vector:

library(colorspace)
img_output <- hex(RGB(c(img[,,1]),c(img[,,2]),c(img[,,3])))

How can I do this?

Upvotes: 2

Views: 670

Answers (1)

sconfluentus
sconfluentus

Reputation: 4993

Just to make this easier to see I used a data frame instead of an array to make what is happening more obvious.

#Creating Data Frame of red, green and blue values 0-1 labeled
img <- data.frame(R= runif(100,0,1),G = runif(100,0,1), B = runif(100,0,1))

#you can use apply also, but wanted to show how it is dropping each
# row into the 'rgb' command.
for (ro in 1:nrow(img)){
  img$hex[ro] <-rgb(img[ro,'R'], img[ro, 'G'], img[ro, 'B'], max=1)
}

Our output:

               R         G           B   hex
      0.23948334 0.4673375 0.479445200 #3D777A
      0.03930279 0.4029776 0.092679483 #0A6718
      0.93748689 0.6637624 0.900167870 #EFA9E6
      0.46137007 0.9688970 0.001738671 #76F700
      0.31737616 0.3566998 0.675646818 #515BAC
      0.62523116 0.3513590 0.035781224 #9F5A09

You can do the same thing with values from 0 to 255 as well:

img <- data.frame(R= as.numeric(sample(0:255, 100)),G = as.numeric(sample(0:255, 100)), B = as.numeric(sample(0:255, 100)))
for (ro in 1:nrow(img)){
  img$hex[ro] <-rgb(img[ro,'R'], img[ro, 'G'], img[ro, 'B'], max=255)
}

The output:

    R   G   B     hex
   175 147 202  #AF93CA
   124  90 183  #7C5AB7
   221 149 110  #DD956E
     0 186  23  #00BA17
    42  37 227  #2A25E3
    31   8 101  #1F0865

You control the parameters of the individual color spaces by setting the max= to suit how your r,g,b values are presented in the original data.

Upvotes: 1

Related Questions