
4.1.5 空间变换
对于灰色图像,可以使用R基础包的t()函数或者EBImage扩展包的transpose()函数进行转置。运行以下程序代码,得到转置后的灰色图像,如图4-14所示。
> img_t <- transpose(img) # 等价于 img_t <- t(img) > plot(img_t)

图4-14 对灰色图像进行转置
对于彩色图像,我们不能使用t()函数,而是需要使用transpose()函数对其进行转置,它能通过交换空间维度来置换图像。运行以下程序代码,得到转置后的彩色图像,如图4-15所示。
> t(imgcol) # 报错 Error in t.default(imgcol) : argument is not a matrix > imgcol_t <- transpose(imgcol) > plot(imgcol_t)

图4-15 对彩色图像进行转置
除了转置,我们还有更多关于图像的空间变换,例如平移、旋转、反射和缩放。translate()函数通过指定的二维向量移动图像平面,裁剪图像区域外的像素,并将进入图像区域的像素设置为背景。参数v是由两个数字组成的向量,表示以像素为单位的平移向量。以下代码可将图像往右移动100像素,往上移动50像素,如图4-16所示。
> img_translate <- translate(img, c(100,50)) > imgcol_translate <- translate(imgcol,c(100,50)) > par(mfrow=c(1,2)) > plot(img_translate) > plot(imgcol_translate) > par(mfrow=c(1,1))

图4-16 图像平移
利用rotate()函数可以将图像顺时针旋转,参数angle表示需要旋转的角度。以下代码可将img图像顺时针旋转30度,如图4-17所示。
> img_rotate <- rotate(img,30) > plot(img_rotate)

图4-17 图像旋转
所有空间变换函数均有参数bg.col,用于设置图像背景色。比如我们可以通过以下代码将旋转后的图像背景色设置为白色,如图4-18所示。
> # 设置背景色为白色 > img_rotate_bg <- rotate(img,30,bg.col = 'white') > plot(img_rotate_bg)

图4-18 调整图像背景色
使用resize()函数可以对图像进行缩放,如果仅提供宽度或者高度之一,则将自动计算另一个尺寸并保持原始宽高比。以下代码会将img、imgcol图像的宽、高均设置为256,如图4-19所示。
> # 调整图像尺寸 > img_resize <- resize(img,w = 256,h = 256) > imgcol_resize <- resize(imgcol,w = 256,h = 256) > par(mfrow=c(1,2)) > plot(img_resize) > plot(imgcol_resize) > par(mfrow=c(1,1))

图4-19 调整图像尺寸
使用flip()和flop()函数可以分别围绕水平轴和垂直轴反射图像,运行以下代码,得到如图4-20所示图像。
> img_flip <- flip(img) > img_flop <- flop(img) > display(combine(img_flip, img_flop), + all=TRUE,method = 'raster')

图4-20 反射图像
使用affine()函数可以实现空间线性变换,其中像素坐标(用矩阵px表示)转换为cbind(px, 1)%*%m。例如,可以通过以下代码实现水平剪切映射,如图4-21所示。
> m <- matrix(c(1, -.5, 128, 0, 1, 0), nrow=3, ncol=2) > img_affine <- affine(img, m) > display(img_affine)