2011-05-31 121 views
2

我正在嘗試創建一個函數,用於根據作業分配的值(scale_zoom)縮放圖像。我不想在這個函數中使用功能resize()內置的MATLAB,所以我試圖插入。任何幫助將不勝感激。這是我到目前爲止有:在MATLAB中調整圖像大小

function pic_new=scale_image(pic,scale_zoom) 
    [row, col]=size(pic) 
    ht_scale=size(pic,1)/scale_zoom*col 
    wid_scale=size(pic,2)/scale_zoom*row 

    size(ht_scale) 
    size(wid_scale) 
    x=(0:scale_zoom)*wid_scale 
    y=(0:scale_zoom)*ht_scale 
    length(x) 
    length(y) 
    %plotvals=0:0.1:scale_zoom (this is not necessary i think) 
    newimg=interp1(pic,x,y,'cubic') 
    image(newimg) 
end 

我想我插很正確:/

+2

你爲什麼不使用interp2() – DanielHsH 2011-05-31 07:19:12

+1

我想你意味着即使您編寫了「resize」,您也不想使用'imresize'。因爲我會爲此使用'imresize'。 – 2011-05-31 15:10:21

回答

6

previously answered一個問題關於scaling images using nearest-neighbor interpolation,等等我使用的代碼和解釋有適用於這裏。主要區別在於最後的插值步驟。這裏是你如何寫你的功能,採用INTERP2和泛化的2-D grayscale or 3-D RGB image of any type

function pic_new = scale_image(pic,scale_zoom) 

    oldSize = size(pic);        %# Old image size 
    newSize = max(floor(scale_zoom.*oldSize(1:2)),1); %# New image size 
    newX = ((1:newSize(2))-0.5)./scale_zoom+0.5; %# New image pixel X coordinates 
    newY = ((1:newSize(1))-0.5)./scale_zoom+0.5; %# New image pixel Y coordinates 
    oldClass = class(pic); %# Original image type 
    pic = double(pic);  %# Convert image to double precision for interpolation 

    if numel(oldSize) == 2 %# Interpolate grayscale image 

    pic_new = interp2(pic,newX,newY(:),'cubic'); 

    else     %# Interpolate RGB image 

    pic_new = zeros([newSize 3]); %# Initialize new image 
    pic_new(:,:,1) = interp2(pic(:,:,1),newX,newY(:),'cubic'); %# Red plane 
    pic_new(:,:,2) = interp2(pic(:,:,2),newX,newY(:),'cubic'); %# Green plane 
    pic_new(:,:,3) = interp2(pic(:,:,3),newX,newY(:),'cubic'); %# Blue plane 

    end 

    pic_new = cast(pic_new,oldClass); %# Convert back to original image type 

end 

而且你可以按如下測試:

img = imread('peppers.png');  %# Load the sample peppers image 
newImage = scale_image(img,0.3); %# Scale it to 30%