rimagepalette

Extract web safe colors from image in R


I have set of images. For each image I need to exract the intensity of so-called "web safe colors" As an output I need a dataframe, where each row is am image, and each column is a color.

Here is how I get safe colors

library(rvest)
library(dplyr)

colors = read_html("https://en.wikipedia.org/wiki/Web_colors#Color_table") %>% 
  html_nodes("h3+ .wikitable td") %>% 
  html_text() %>% 
  trimws()

Here is an example of image:

library(magick)
im = image_read("https://farm4.staticflickr.com/3579/3370591414_f321bd33ff_z.jpg")

I can transform it to different number of color like this:

im %>%
  image_quantize(max=12)

But since I need to compare images, I want each image to be presented in the same palette (and I've chose web safe palette).


Solution

  • So, finally I end up with this. Not exactly the same that I wanted, but works.

      # recolor image 
      
      image_id = im
      
      num_vector = as.numeric(img_vector)*255
      num_vector = round(num_vector / int) * int
      
      #loop for pixels
      for(i in 1:90){
        
        for(j in 1:120){
          
          pixel = num_vector[i,j,] 
          whichcolor = which(tmp$rgb == paste0(pixel, collapse = "|"))
          color = tmp$color_id[whichcolor]
          result = rbind(result, data.frame(image_id, i, j, color))
          
        }
        
      }