在R中调整图像大小

19

我正在尝试使用R处理一些图像数据,但无法弄清如何调整图像大小以确保它们都具有相同的尺寸。

在Python中,我解决了这个问题,方法如下:

from PIL import Image
import numpy as np

size = (100, 100)
img = Image.open(filename)
img = img.resize(size)
img = np.array(img.getdata())

在R中,我一直无法找到一个能够完成同样功能的库。我所能做到的最远的是:

library(jpeg)

img <- readJPEG(filename)
# Need something here to resize
img <- as.matrix(img)
最简单的方法是使用像Pillow这样的库来调用,但正如我所说,我似乎找不到任何东西。
谢谢。
6个回答

25

您可以借助生物计算包EBImage轻松实现这一点,该软件包是R的图像处理和分析工具箱。要安装软件包,请使用以下命令:

source("http://bioconductor.org/biocLite.R")
biocLite("EBImage")
你可以使用 EBImage 提供的功能来加载和调整图片大小,就像以下示例一样。
library("EBImage")

x <- readImage(system.file("images", "sample-color.png", package="EBImage"))

# width and height of the original image
dim(x)[1:2]

# scale to a specific width and height
y <- resize(x, w = 200, h = 100)

# scale by 50%; the height is determined automatically so that
# the aspect ratio is preserved
y <- resize(x, dim(x)[1]/2)

# show the scaled image
display(y)

# extract the pixel array
z <- imageData(y)

# or
z <- as.array(y)

要了解EBImage提供的功能示例,请参见包vignette


11

imager非常适合,它隐藏了所有关于样条、插值的细节,并且简单地将图像存储在一个四维数组中(第四维用于视频)。

library(imager)

im <- load.image(my_file)

thmb <- resize(im,round(width(im)/10),round(height(im)/10))

plot(im)
plot(thmb,main="Thumbnail")

更多信息可以在官方介绍页面找到。


8
这些选项是否满足您的需求:
library(jpeg)

img <- readJPEG(system.file("img", "Rlogo.jpg", package="jpeg"))

# Set image size in pixels
for (i in 3:6) {
  jpeg(paste0("Pixels",i,".jpeg"), width=200*i, height=200*i)
  plot(as.raster(img))
  dev.off()
}

# Set image size in inches (also need to set resolution in this case)
for (i in 3:6) {
  jpeg(paste0("Inches",i,".jpeg"), width=i, height=i, unit="in", res=600)
  plot(as.raster(img))
  dev.off()
}

你还可以保存为其他格式:png, bmp, tiff, pdf。输入?jpeg以获取保存为位图格式的帮助信息,输入?pdf以获取保存为pdf的帮助信息。

这对我很有效。我更喜欢只使用必要的库。另一个提示:在绘图线之前使用 par(mar=c(0,0,0,0)) 可以去除不需要的空白。 - Arnold Cross

5
我使用以下代码来重采样矩阵。如果您有一个jpeg对象,您可以分别对每个颜色通道进行操作。
策略如下:
给定一个维度为a和b的矩阵m以及新的维度a.new和b.new
1.定义新网格
x.new <- seq(1,a,length.out=a.new)
y.new <- seq(1,a,length.out=b.new)
  1. xy方向上将原始矩阵重采样两次
V <- apply(V,2,FUN=function(y,x,xout) return(spline(x,y,xout=xout)$y),x,x.new)
V <- t(apply(V,1,FUN=function(y,x,xout) return(spline(x,y,xout=xout)$y),d,y.new))

在这里,我选择了样条插值,但你也可以使用带有approx()的线性插值。你还可以使用image(x = x.new, y = y.new, z = V)函数获得额外的x和y轴以进行绘图。

祝一切顺利。


2
受Seily启发,调整灰度图像大小。
resize = function(img, new_width, new_height) {
  new_img = apply(img, 2, function(y){return (spline(y, n = new_height)$y)})
  new_img = t(apply(new_img, 1, function(y){return (spline(y, n = new_width)$y)}))

  new_img[new_img < 0] = 0
  new_img = round(new_img)

  return (new_img)
}

0

使用包imager和单个参数

library(imager)

im <- load.image(pict)

thmb <- im %>% imresize(0.1)

plot(im)
plot(thmb,main="Thumbnail")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接