Reputation: 89
I would like to have R detect a given color in a section of an image.
I've been reading about RGB schemes, but I thought there would maybe a package or a way to have R detect a cluster of pixels where, for example, the color yellow takes place.
Is there a solution or am I just trapped in RGB?
Thanks.
Upvotes: 3
Views: 2254
Reputation: 841
Here you go:
install.packages('raster')
library(raster)
#Get some data
duck.jpg<-tempfile()
download.file('http://www.pilgrimshospices.org/wp-content/uploads/Pilgrims-Hospice-Duck.jpg',duck.jpg,mode="wb")
#Plug it into a stack object
duck.raster<-stack(duck.jpg)
names(duck.raster)<-c('r','g','b')
#Look at it
plotRGB(duck.raster)
duck.yellow<-duck.raster
duck.yellow$Yellow_spots<-0
duck.yellow$Yellow_spots[duck.yellow$r<250&duck.yellow$g<250&duck.yellow$b>5]<-1
plot(duck.yellow$Yellow_spots)
So, just a few teachable points here. A digital image is basically a bucket for holding pixel values. So all you need to do to subset a raster (read: digital image), is use some tool to read it into R; decide how you want to subset it; and subset it in the same way you would subset any other data in R. Another way to think about a raster in R is a stack of same size matrices, with the number of matrices in the stack as the number of bands in the image. In this manner, you can manipulate the data as you would manipulate any other matrix in R.
Upvotes: 5