代码之家  ›  专栏  ›  技术社区  ›  cooldood3490

打印多个光栅图像时填充空白

  •  0
  • cooldood3490  · 技术社区  · 7 年前

    enter image description here

    我指定 mar=c(0,0,1,0)

    以下是我目前掌握的情况:

    library(EBImage)
    library(png)
    
    pngs<-lapply(seq(1:4), function(x) {
       readPNG(system.file("images", "sample-color.png", package="EBImage"))
    })
    
    par(mfrow=c(2,2), mar=c(0, 0, 1, 0))
    invisible(sapply(seq_along(pngs), function(i) {
      plot.new()
      plot.window(xlim=c(0, 1), ylim=c(0, 1), asp=1)
      rasterImage(pngs[[i]], 0, 0, 1, 1)
      title(paste0(letters[i], '. Image ', i), font.main=2)
    }))
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Nairolf    7 年前

    因为 asp=1 图像保持了图像的原始纵横比 512:768 在你的例子中。相反,默认打印设备的纵横比似乎接近 1:1 . 这不匹配,导致空白空间。

    1. asp=NA 通过扭曲图像,让图像使用设备的整个空间。
    2. width 和 height dev.new() . 例如:

      library(EBImage)
      library(png)
      png <- readPNG(system.file("images", "sample-color.png", package="EBImage"))
      dev.new(width=4.5, height=8)
      par(mfrow=c(2,2), mar=c(0, 0, 1, 0))
      for(i in seq_len(4)){
          plot.new()
          plot.window(xlim=c(0, 1), ylim=c(0, 1), asp=1)
          rasterImage(png, 0, 0, 1, 1)
          title(paste0("Image ", i))
      }
      
        2
  •  1
  •   David O    7 年前

    png 包不是必需的,下面是另一个利用 EBImage . 除非有意变换图像,否则EBImage将保持纵横比。

    此解决方案需要更多的工作来放置打印标签 text() 但增加的成本可能会被更大的灵活性所抵消。

    # Starting from EBImage
      library(EBImage)
      fn <- system.file("images", "sample-color.png", package="EBImage")
    
    # Single EBImage object with same four pictures
      pngs <- readImage(rep(fn, 4))
    
    # Select spacing and margin for EBImage display/plot function
      spacing <- 50 # pixels between images
      margin <- 50 # pixels around edge
      nx <- 2 # number of rows for composite
      ny <- 2 # number of columns for composite
      dm <- dim(pngs)
      nframes <- dm[length(dm)]
      yadj <- -0.2 # offset for labels in y direction
    
    # Indices, coordinates, and labels for text
      index <- seq_len(nframes)
      ix <- (index - 1)%%nx
      iy <- (index - 1)%/%nx
      xx <- ix*(dm[1] + spacing) + dm[1]/2
      yy <- iy*(dm[2] + spacing)
      labs <- sprintf("%s. Image %d", letters[index], index)
    
    # Plot composite and add "titles" with text() function
      plot(pngs, all = TRUE, nx = nx, margin = margin, spacing = spacing)
      text(xx, yy, labs, adj = c(0.5, yadj))
    
    # To eliminate ANY space in the composite make the following
    # changes and re-run the code from "# Indices, coordinates..."
      spacing <- 0
      margin <- 0
      yadj <- 1.2
      dev.new(width = nx*dm[1]/200, height = ny*dm[2]/200) # 200 dpi image