如何使用R的pixmap包提取像素数据?

5
如何使用R的pixmap包提取像素数据?
首先,使用以下代码读取图像文件: picture <- read.pnm("picture.pgm") picture Pixmap image Type : pixmapGrey Size : 749x745 Resolution : 1x1 Bounding box : 0 0 745 749
然后,如何将像素数据提取到矩阵中?
2个回答

4

您可以通过 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

如果您想更直接地访问数据,请使用S4访问器(@),例如:

>  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

2

试试这个:

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接