Reputation: 598
I use the biOps package in R to extract RGB values from an image. As an example, I have an image of 10x10 pixels. The result is an array of x[1:10,1:10,1]
for Red, x[1:10,1:10,2]
for Green and x[1:10,1:10,3]
for Blue. I want to convert this to a dataframe like below:
(Pixel X position, Pixel Y position, Red value, Green Value, Blue value)
X Y R G B
1 1 255 255 255
1 2 255 255 255
1 3 0 0 0
...
10 10 255 255 255
IMPORTANT: I do not always know the size of the pixels, I use 10x10 as an example only.
How do I do this in R? Any help will be greatly appreciated.
Cheers B
Upvotes: 0
Views: 1067
Reputation: 206536
The reshape2
library can make this easy. First let's create some test data
x <- array(sapply(1:3, function(i) sample(0:9, 100, replace=T)+i*10), dim=c(10,10,3))
This is an array x
like yours with dim c(10,10,3)
. Now we can melt the data and cast it how we like
mm <- melt(x, varnames=c("X","Y","Color"))
mm$Color <- factor(mm$Color, levels=1:3, labels=c("Red","Blue","Green"))
xx <- dcast(mm, X+Y~Color)
head(xx)
And that produces data like
X Y Red Blue Green
1 1 1 10 26 33
2 1 2 12 23 31
3 1 3 13 25 32
4 1 4 18 24 31
5 1 5 18 26 35
6 1 6 14 24 36
Note that the reshape
command didn't care that is was 10x10
it will just unwarp each dimension of your array. You will just want to make sure the third dimension is 3 to correspond to the three colors.
Upvotes: 2