How to extract pixel data Use R pixmap package?

How to extract pixel data Use R pixmap package?

so I read the image file using:

picture <- read.pnm ("picture.pgm") picture Image in pixels Type: pixmapGrey Size: 749x745 Resolution: 1x1 Boundary box: 0 0 745 749

How to extract pixel data into some matrix?

+5
source share
2 answers

You can get the data as a two-dimensional matrix for a grayscale image or a three-dimensional array for a color image with 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 data more directly, use S4 accessor ( @), for example:

>  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
+4
source

Try the following:

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)
+1
source

All Articles