How to extract the pixel data Use R's pixmap package?

Helen Peterson picture Helen Peterson · May 22, 2011 · Viewed 7k times · Source

How to extract the pixel data Use R's pixmap package?

so I read the image file using:

picture <- read.pnm("picture.pgm") picture Pixmap image Type : pixmapGrey Size : 749x745 Resolution : 1x1 Bounding box : 0 0 745 749

How to extract the pixel data into some matrix?

Answer

kohske picture kohske · May 22, 2011

You can get the data as a 2-D matrix for grayscale image or 3-D array for color image by getChannels.

>  x <- read.pnm(system.file("pictures/logo.ppm", package="pixmap")[1])
>  y <- getChannels(x)
>  class(y)
[1] "array"
>  dim(y)
[1]  77 101   3
>  
>  x <- read.pnm(system.file("pictures/logo.pgm", package="pixmap")[1])
>  y <- getChannels(x)
>  class(y)
[1] "matrix"
>  dim(y)
[1]  77 101

if you want to access the data more directly, use S4 accessor (@), e.g.:

>  x <- read.pnm(system.file("pictures/logo.ppm", package="pixmap")[1])
>  str(x)
Formal class 'pixmapRGB' [package "pixmap"] with 8 slots
  ..@ red     : num [1:77, 1:101] 1 1 1 1 1 1 1 1 1 1 ...
  ..@ green   : num [1:77, 1:101] 1 1 1 1 1 1 1 1 1 1 ...
  ..@ blue    : num [1:77, 1:101] 1 1 0.992 0.992 1 ...
  ..@ channels: chr [1:3] "red" "green" "blue"
  ..@ size    : int [1:2] 77 101
  ..@ cellres : num [1:2] 1 1
  ..@ bbox    : num [1:4] 0 0 101 77
  ..@ bbcent  : logi FALSE
>  x@size
[1]  77 101