Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

pixmap

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?

like image 316
Helen Peterson Avatar asked May 21 '11 23:05

Helen Peterson


2 Answers

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
like image 71
kohske Avatar answered Sep 21 '22 04:09

kohske


Try this:

library(pixmap)   

picture <- read.pnm("picture.pgm")   

#Take a look at what you can get (notice the "@" symbols) 
str(picture)   

#If you want to build a matrix using the dimensions of "picture"....    
picture@size    
mat1 <- matrix(NA, picture@size[1], picture@size[2]) 

#If you want to build a matrix directly from "grey".....  
mat <- picture@grey    

#Take a look at mat
head(mat)
like image 37
bill_080 Avatar answered Sep 19 '22 04:09

bill_080