管理和理解数据(第三课)-数组和图片处理

  • 创建一个三维数组
ar <- array(1:24,dim=c(2,4,3))

数组的筛选与矩阵的几乎一致。

  • 在EBImage包(或者其他类似的包里),图片处理经常涉及到三维数组。比如说,我们想要来处理下面这个图片:
    这里写图片描述
library(EBImage)
pic <- readImage("images/pic_svd.jpg")
display(pic)

当我们查看pic变量的时候,我们会发现pic有一个名叫.Data的接口,这是一个三维的数组。

## Formal class 'Image' [package "EBImage"] with 2 slots
##   ..@ .Data    : num [1:278, 1:366, 1:3] 0.996 0.996 0.996 0.996 0.996 ...
##   ..@ colormode: int 2

从.Data中,我们可以判断这个图片的尺寸是278*366。
实际上,我们可以简单的认为.Data的三个矩阵分别表示红、绿、蓝色。

picList <- list([email protected][,,1],[email protected][,,2],[email protected][,,3])
display(combine(picList),all=T)

这里写图片描述

  • 加强红色:
tmpPic <- pic
[email protected][,,1] <- [email protected][,,1]*2
display(tmpPic)

这里写图片描述
其余关于色彩上的变化类似,都可以通过调节@.Data来实现

  • EBImage同样有将图片翻转的方法:
picList <- list(pic,flip(pic))
display(combine(picList),all=T)

这里写图片描述

  • 还能把图片对称翻转
picList <- list(pic,flop(pic))
display(combine(picList),all=T)

这里写图片描述

  • 我们试着自己来实现以下翻转方法:
myFlip <- function(img)
{
  if(class(img)!="Image") stop("parameter's class is  not Image")
  wd <- dim([email protected])
  img@.Data[,1:wd[2],] <- img@.Data[,wd[2]:1,]
  img
}
picList <- list(pic,myFlip(pic))
display(combine(picList),all=T)

同理,flop方法也可以同样的实现:

myFlop <- function(img)
{
  if(class(img)!="Image") stop("parameter's class is Image")
  wd <- dim([email protected])
  [email protected][1:wd[1],,] <- [email protected][wd[1]:1,,]
  img
}
picList <- list(pic,myFlop(pic))
display(combine(picList),all=T)
  • 此外,图片的旋转也挺有趣的:
display(rotate(pic,45),all=T)

这里写图片描述

  • 倒置图片
tmpPic <- pic
tmpPic@.Data <- 1 - [email protected]
display(tmpPic)

这里写图片描述

  • 灰度化图片

`
tmpPic <- pic
[email protected][,,] <- [email protected][,,1]*0.3+
[email protected][,,2]*0.59 + [email protected][,,3]*0.11
display(tmpPic)
这里写图片描述`

猜你喜欢

转载自blog.csdn.net/weixin_40514680/article/details/80393151