我正在尝试使用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())
Run Code Online (Sandbox Code Playgroud)
在R中,我无法找到能够完成同样事情的库.我能得到的最远的是:
library(jpeg)
img <- readJPEG(filename)
# Need something here to resize
img <- as.matrix(img)
Run Code Online (Sandbox Code Playgroud)
最简单的方法是像Pillow这样的库我可以打电话,但正如我所说,我似乎无法找到任何东西.
谢谢,
aol*_*les 21
借助Bioconductor软件包EBImage(R的图像处理和分析工具箱),您可以轻松完成此任务.要安装包使用:
source("http://bioconductor.org/biocLite.R")
biocLite("EBImage")
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用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)
Run Code Online (Sandbox Code Playgroud)
有关EBImage提供的功能的更多示例,请参阅包装插图.
该软件包imager非常适合隐藏所有关于样条线,插值的细节,并简单地将图像存储在一个4维数组中(第四维用于视频)
library(imager)
im <- load.image(my_file)
thmb <- resize(im,round(width(im)/10),round(height(im)/10))
plot(im)
plot(thmb,main="Thumbnail")
Run Code Online (Sandbox Code Playgroud)
更多信息可以在这里找到:官方介绍.
这些选项涵盖了您的需求:
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()
}
Run Code Online (Sandbox Code Playgroud)
您还可以保存为其他格式; png,bmp,tiff,pdf.?jpeg将显示保存位图格式的帮助.?pdf有关以pdf格式保存的帮助.
我使用以下代码对矩阵进行重新采样。如果您有一个 jpeg 对象,您可以对每个颜色通道单独执行此操作。
策略如下:
给定一个m具有维度a和的矩阵b,以及新维度a.new和b.new
Run Code Online (Sandbox Code Playgroud)x.new <- seq(1,a,length.out=a.new) y.new <- seq(1,a,length.out=b.new)
x在和y方向上对原始矩阵重新采样两次Run Code Online (Sandbox Code Playgroud)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))
这里我选择样条插值,但您也可以使用线性插值apporx()。您将额外获得一个 x 轴和 y 轴,用于使用该image(x = x.new, y = y.new, z = V)函数进行绘图。
最好的。