2016-03-04 141 views
10

我正嘗試在R中使用一些圖像數據,並且無法弄清楚如何調整圖像大小以確保它們的大小完全相同。在R中調整大小圖像

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,我一直無法找到一個能夠完成同樣的事情庫:

在Python,我如下走近這個問題。 我已經能夠獲得最遠的是:

library(jpeg) 

img <- readJPEG(filename) 
# Need something here to resize 
img <- as.matrix(img) 

最簡單的辦法是像枕頭,我可以調用一個庫,但正如我所說,我似乎無法找到任何東西。

感謝,

回答

14

您可以輕鬆地與Bioconductor的包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

+0

謝謝 - 這正是我一直在尋找 –

5

你對這些選項包括你所需要的:

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。

2

我使用下面的代碼來重新採樣矩陣。如果你有一個jpeg對象,你可以爲每個顏色通道個體做這件事。

的策略如下:

給定矩陣m與尺寸ab和新的層面a.newb.new

  1. 定義新的網格
x.new <- seq(1,a,length.out=a.new) 
y.new <- seq(1,a,length.out=b.new) 
x
  • 重新採樣原始矩陣兩次,並在y方向
  • 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)函數。

    最好。

    7

    封裝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") 
    

    更多信息可以在這裏找到:on the official introduction.

    0

    靈感來自西里,調整灰度級圖像的大小。

    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) 
    }