天天看點

基于MATLAB實作輸入圖像的雙線性插值

以下為雙線性插值算法matlab實作的簡單總結,以便之後複習。

Bilinear interpolation is a more important interpolation method, especially in the field of digital image processing. Now I introduce the algorithm derivation of bilinear interpolation, and use MATLAB to implement the algorithm. Bilinear interpolation is also called quadratic linear interpolation. Its main idea is to use the four pixels around a pixel to calculate floating-point coordinate pixel values.

基于MATLAB實作輸入圖像的雙線性插值

As shown in FIG, the pixel values of f1 and f2 are respectively obtained by a linear interpolation, and then the pixel values of f are obtained by linear interpolation for f1 and f2. This is the principle of bilinear interpolation. We can use the following formula to show the process of solving:

基于MATLAB實作輸入圖像的雙線性插值

The original image and interpolated resultant image are as follows:

基于MATLAB實作輸入圖像的雙線性插值
基于MATLAB實作輸入圖像的雙線性插值

參考代碼見下:

function [ ZI ] = interpolation( I,zmf )

%% ----------------------雙線性插值法處理圖像---------------------------
% Input:
%       I:圖像檔案名或矩陣(整數值(0~255))
%       zmf:縮放因子,即縮放的倍數
% Output:    
%       對矩陣I進行zmf倍的縮放并顯示

%% 指令行中輸入以下指令運作即可:
%  interpolation('flower2.png', 4);

%% Step1 對資料進行預處理
if ~exist('I','var') || isempty(I)
    error('輸入圖像I未定義或為空!');
end
if ~exist('zmf','var') || isempty(zmf) || numel(zmf) ~= 1
     error('位移矢量zmf未定義或為空或zmf中的元素超過2!');
end
if ischar(I)
    [I,M] = imread(I);
end
if zmf <= 0
     error('縮放倍數zmf的值應該大于0!');
end

%% Step2 通過原始圖像和縮放因子得到新圖像的大小,并建立新圖像。
[IH,IW,ID] = size(I);
ZIH = round(IH*zmf);     % 計算縮放後的圖像高度,最近取整
ZIW = round(IW*zmf);     % 計算縮放後的圖像寬度,最近取整
ZI = zeros(ZIH,ZIW,ID);  % 建立新圖像

%% Step3 擴充矩陣I邊緣
%雙線性插值是用待求值點周圍四個點的值來計算的,當新圖像上的像素點映射到原圖像的邊界時,邊界擴充保證了計算能正确進行,而不會溢出。
IT = zeros(IH+2,IW+2,ID);
IT(2:IH+1,2:IW+1,:) = I;
IT(1,2:IW+1,:)=I(1,:,:);
IT(IH+2,2:IW+1,:)=I(IH,:,:);
IT(2:IH+1,1,:)=I(:,1,:);
IT(2:IH+1,IW+2,:)=I(:,IW,:);
IT(1,1,:) = I(1,1,:);
IT(1,IW+2,:) = I(1,IW,:);
IT(IH+2,1,:) = I(IH,1,:);
IT(IH+2,IW+2,:) = I(IH,IW,:);

%% Step4 由新圖像的某個像素(zi,zj)映射到原始圖像(ii,jj)處,并插值。
for zj = 1:ZIW         % 對圖像進行按列逐元素掃描
    for zi = 1:ZIH
        ii = (zi-1)/zmf; jj = (zj-1)/zmf;
        i = floor(ii); j = floor(jj);    % 向下取整
        u = ii - i; v = jj - j;
        i = i + 1; j = j + 1;
        ZI(zi,zj,:) = (1-u)*(1-v)*IT(i,j,:) + (1-u)*v*IT(i,j+1,:) + u*(1-v)*IT(i+1,j,:) + u*v*IT(i+1,j+1,:);
    end
end

ZI = uint8(ZI);

%% 顯示處理前後的圖像
figure;
imshow(I,M);
axis on;
title(['original image(',num2str(IH),'*',num2str(IW),'*',num2str(ID),')']);
figure;
imshow(ZI,M);
axis on;
title(['interpolated resultant image(',num2str(ZIH),'*',num2str(ZIW),'*',num2str(ID)',')']);
end  
           

繼續閱讀