我想创建一个由 9 个图像组成的网格,它们之间的间距相等。到目前为止,我设法让一些东西可以与 par()
和 layout()
一起使用。
layout(matrix(1:9, widths=rep(lcm(4),9), heights=rep(lcm(3),9))
for (i in 1:9) {
imNew <- readImage(img_ar[i])
EBImage::display(imNew, method="raster")
}
给我这个
使用标准价时:
layout(matrix(1:9, widths=rep(lcm(4),9), heights=rep(lcm(3),9))
for (i in 1:9) {
imNew <- readImage(img_ar[i])
EBImage::display(imNew,method="raster")
}
给了我这个:
我还尝试了 par()
的不同选项,例如 oma
、mai
和 mar
但这些都没有' t 改变各个图像之间的间距。我喜欢的是各个图像之间的距离相等,如下所示:
有人可以帮我吗?
最佳答案
您可以使用您最初的想法通过在布局中包含额外的空行和列来分隔图像,如下例所示。但请注意,为了实现相等的水平和垂直间距,您需要调整设备尺寸。
library(EBImage)
# load sample image
img <- readImage(system.file("images", "sample-color.png", package="EBImage"))
# downsample to reduce memory consumption and for faster processing
img <- resize(img, 192)
# build the layout matrix with additional separating cells
nx <- 4 # number of images in a row
ny <- 3 # number of images in a column
cols <- 2*nx-1
rows <- 2*ny-1
m <- matrix(0, cols, rows)
m[2*(1:nx)-1, 2*(1:ny)-1] <- 1:(nx*ny)
m <- t(m)
# relative spacing
pad <- .1
w <- rep(1, cols)
w[!(1:cols)%%2] <- pad
h <- rep(1, rows)
h[!(1:rows)%%2] <- pad * dim(img)[1L]/dim(img)[2L]
layout(m, widths = w, heights = h)
layout.show(nx*ny)
for (i in 1:(nx*ny)) {
display(img, method="raster")
}
更好的方法是在图像堆栈上使用 display()
。然后可以通过设置 all=TRUE
以网格形式显示各个帧。
## construct sample image stack
img_stack <- combine(replicate(nx*ny, img, simplify=FALSE))
display(img_stack, method="raster", all=TRUE)
不幸的是,直到最近还无法调整框架之间的间距。为了实现这一点,我向 display()
添加了一个参数来指定间距
。目前,此新功能已在 EBImage 的开发版本中提供,可以从 GitHub devtools::install_github("aoles/EBImage")
或从 Bioconductor devel branch 获取.
间距可以以帧尺寸的分数(正数 <1)或以像素为单位(数字 >=1)提供。此外,您可以通过提供向量来获得不同的水平和垂直间隔,例如spacing = (10, 20)
会将列分隔 10 像素,将行分隔 20 像素。
display(img_stack, method="raster", all=TRUE, spacing=.1)
此外,您还可以在网格周围添加margin
,并通过nx
控制其布局。背景可以通过传递给 par()
的 bg
来设置。
最后,在网格中绘制图像的一种完全不同的方式是使用tile
构建一个大的合成图像。例如,当将结果保存到文件时,此方法可能很有用。请注意整个网格周围的附加边框。
## tiled composite image
img_tiles <- tile(img_stack, nx=nx, lwd=20, fg.col="white", bg.col="white")
display(img_tiles, method="raster")
关于r - 使用layout()和display()显示等距图像的网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40301667/