【问题标题】:How to remove the margin around an image crated using png() in R如何删除在 R 中使用 png() 创建的图像周围的边距
【发布时间】:2020-06-11 07:25:15
【问题描述】:

我正在尝试使用 R 覆盖两个 PNG 图像(不透明)。为此,我的逻辑如下:我使用 readPNG() 读取两个图像。然后,我使用 abind() 添加一个 alpha 通道,例如,0.5 以使图像半透明。到目前为止,所有这些都运行良好,我的问题是当我使用 png() 覆盖图像时,输出图像有一个白边。这总是会发生,即使我使用par() 将边距设置为0。我错过了什么?

请在下面找到一个最小的工作示例:

library("png") 
library("abind")

# Download two random pictures
pngURL1 <- "https://imgur.com/download/0ljEVEW"
pngURL2 <- "https://imgur.com/download/oShoMag"
download.file(pngURL1, "temp1.png", mode = "wb")
download.file(pngURL2, "temp2.png", mode = "wb")

# Load downloaded images and add alpha channel
img1 = readPNG("temp1.png")
img1 = abind::abind(img1, img1[,,1]) # add an alpha channel
img2 = readPNG("temp2.png")
img2 = abind::abind(img2, img2[,,1]) # add an alpha channel

# Make semi-transparent
img1[,,4] <- 0.5
img2[,,4] <- 0.5

# Create output image
png('test.png', width = 480, height = 360)
par(mar = c(0,0,0,0))
plot.new()
rasterImage(img1, 0, 0, 1, 1)
rasterImage(img2, 0, 0, 1, 1)
dev.off()

这将创建以下输出:Example image with unwanted margin 我想去掉边距,这样我只得到一个与我使用的输入图像具有完全相同尺寸的 PNG 图像。

非常感谢您的帮助!

【问题讨论】:

    标签: r image image-processing png


    【解决方案1】:

    不需要的边距是轴范围计算的结果。默认情况下,轴范围超出数据范围 4%。为了解决这个问题,您可以将par 中的xaxsyaxs 参数设置为i -- 内部样式。

    对于您的示例,它将是:

    par(mar = c(0,0,0,0), xaxs="i", yaxs="i")
    

    结果是:

    【讨论】:

    • 太棒了!非常感谢,我不知道这种默认行为以及如何避免它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-22
    • 2020-03-02
    相关资源
    最近更新 更多