2013-10-26 33 views
0

我有這個過濾功能,採取輸入圖像,使用給定的內核執行卷積,並返回結果圖像。但是,我似乎無法解決如何使它具有不同的內核大小。例如,代碼中未使用預定義的3x3內核,可能需要5x5或7x7。然後用戶可以輸入他們想要的內核/過濾器的類型(取決於預期的效果)。我似乎無法把它放在頭上。我對matlab很陌生。功能在輸入圖像和不同的內核大小

function [newImg] = kernelFunc(imgB) 


img=imread(imgB); 

figure,imshow(img); 




img2=zeros(size(img)+2); 

newImg=zeros(size(img)); 




for rgb=1:3 

     for x=1:size(img,1) 

      for y=1:size(img,2) 

       img2(x+1,y+1,rgb)=img(x,y,rgb); 

      end 

     end 

end 


for rgb=1:3 
    for i= 1:size(img2,1)-2 

     for j=1:size(img2,2)-2 

      window=zeros(9,1); 

      inc=1; 

      for x=1:3 

       for y=1:3 

        window(inc)=img2(i+x-1,j+y-1,rgb); 

        inc=inc+1; 

       end 

      end 

      kernel=[1;2;1;2;4;2;1;2;1]/16; 



      med=window.*kernel; 

      disp(med); 

      med=sum(med); 

      med=floor(med); 


      newImg(i,j,rgb)=med; 



     end 

    end 

end 


newImg=uint8(newImg); 

figure,imshow(newImg); 

end 
+0

爲什麼不使用'conv2'? http://www.mathworks.es/es/help/matlab/ref/conv2.html –

回答

0

我已經評論了代碼並標記了要更改的地方<--。本例中的kernel是3 * 3 = 9個元素的列向量。除了更改內核本身外,還可能需要更改圖像周圍的零填充量。例如,對於一個5x5內核,你需要兩行和兩列填充而不是一個。然後更新我標記爲「抓取每個像素」的內部循環,以拉出內核大小的區域(例如,針對5x5內核的for x=1:5for y=1:5)。實際卷積不變。

提醒:該功能需要一個uint8(0..255值)的RGB圖像。 windowkerneldouble,所以trunc在將新像素值置於uint8 newImg之前關閉任何小數部分。

function [newImg] = kernelFunc(imgB) 

img=imread(imgB); 
figure,imshow(img); 

img2=zeros(size(img)+2); % one extra column on each side, and one extra 
          % row top and bottom. <-- May need more padding. 
newImg=zeros(size(img)); % the destination 

% Pad the image with zeros at the left and top (transform img->img2) 
for rgb=1:3 
    for x=1:size(img,1) %for each row 
     for y=1:size(img,2) %for each column 
      img2(x+1,y+1,rgb)=img(x,y,rgb); % <-- adjust per kernel size 
     end 
    end 
end 

% Process the padded image (img2->newImg) 
for rgb=1:3 
    for i= 1:size(img2,1)-2   % for each row 
     for j=1:size(img2,2)-2  % for each column 

      % Build a row vector of the pixels to be convolved. 
      window=zeros(9,1);  % <-- 9=kernel size 
      inc=1; 
      for x=1:3    % <-- grab each pixel 
       for y=1:3   % <-- under the kernel 
        window(inc)=img2(i+x-1,j+y-1,rgb); 
        inc=inc+1; 
       end 
      end 

      kernel=[1;2;1;2;4;2;1;2;1]/16; % <-- the kernel itself 

      med=window.*kernel;  % start the convolution 
      disp(med); 
      med=sum(med);   % finish the convolution 
      med=floor(med);   % fit the pixels back into uint8. 

      newImg(i,j,rgb)=med; % store the result 

     end %for each column 
    end %for each row 
end %for each color channel 


newImg=uint8(newImg); 
figure,imshow(newImg); 

end