How to get pixel data from an image using R

限于喜欢 提交于 2019-11-27 20:55:48

First I generate an example png image :

png("/tmp/test.png")
plot(rnorm(100))
dev.off()

Then I convert it to a format readable by pixmap : here I convert the png to a ppm file as I want to keep colors information. I use ImageMagick from the command line, but you can use whatever program you want :

$ convert /tmp/test.png /tmp/test.ppm

Next, you can read the image with the read.pnm function from the pixmap package :

x <- read.pnm("/tmp/test.ppm")

And then, you can use the x@red, x@blue, x@green slots (or x@grey for a greyscale image) to get the pixels value for each channel as a matrix. You can check that the dimensions of the matrices are the same as the size of your picture :

dim(x@red)
[1] 480 480

Take this tiny sample 3x3 pixel png image:

Then:

library('png')
download.file('http://i.stack.imgur.com/hakvE.png', 'sample.png')
img <- readPNG('sample.png')
pix.top.left <- img[1,1,]     # row 1, column 1
pix.bottom.left <- img[3,1,]  # row 3, column 1
pix.top.right <- img[1,3,]    # row 1, column 3

If you're reading a PNG image with alpha channel (as the sample image above), then each of the pix. variables is a vector with four entries, each entry corresponding to Red ,Green, Blue and Alpha values of the pixel.

> pix.top.left
[1] 1 0 0 1
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!