Reputation: 59
I'm trying to obtain the percentage of each color which compose a given picture. I get the RGB matrix using this code:
library(jpeg)
img <- readJPEG("C:/Users/Pictures/img.jpg")
dim(img)
#145 371 3
img<-img*255
#this operation is necessary to obtain an RBG scale
At this step I'm not sure which is the right way to go ahead. Anyway, I would like to obtain someting like this:
Count RGB vector
200614 (255,255,255)
4758 (253,253,218)
4312 (250,250,229)
1821 (235,237,242)
1776 (212,214,226)
...
and then I can calculate the percentage of each color. Lastly I'll try to associate a label to each RGB vector.
Anyone can help me?
Upvotes: 1
Views: 1751
Reputation: 1545
You can easily count colors with table
after converting the pixel array to #rrggbb values with as.raster
(note that you don't need to scale the values by multiplying them by 255). Individual color components from hex color strings can be obtained by col2rgb
.
library(jpeg)
img <- readJPEG("C:/Users/Pictures/img.jpg")
# Convert the 3D array to a matrix of #rrggbb values
img <- as.raster(img)
# Create a count table
tab <- table(img)
# Convert to a data.frame
tab <- data.frame(Color = names(tab), Count = as.integer(tab))
# Extract red/green/blue values
RGB <- t(col2rgb(tab$Color))
tab <- cbind(tab, RGB)
# Preview
head(tab)
Upvotes: 9