[MATLAB]领域插值和线性插值
先由目标图像的坐标得到原图像的坐标,然后将原图像坐标点的像素值赋给新的图像.
1.领域插值
I1=imread('flower.jpg');%读入彩色图像
I=rgb2gray(I1);%转换成灰度图像,若原图为灰度图,可省去此行
[nrows,ncols]=size(I);
K = str2double(inputdlg('请输入缩放倍数(缩小请用小于1的倍数表示)', 'INPUT scale factor', 1, {'0.5'}));
width = K * nrows; % K为缩放的倍数,确定输出矩阵大小
height = K * ncols;
J = uint8(zeros(width,height)); %定义输出图像矩阵
widthScale = nrows/width;
heightScale = ncols/height;
for x = 5:width - 5 %为防止矩阵溢出而选择的参数5
for y = 5:height - 5
xx = x * widthScale; %xx,yy为原坐标,x,y为新坐标
yy = y * heightScale;
if (xx/double(uint16(xx)) == 1.0) & (yy/double(uint16(yy)) == 1.0)
J(x,y) = I(int16(xx),int16(yy));%若yy为整数,则直接赋值过去
else
a = double(round(xx));
b = double(round(yy)); %若不是整数四舍五入后把临近值赋过去
J(x,y) = I(a,b);
end
end
end
imshow(I); %输出原图像
figure;
imshow(J); %输出缩放后图像
二、双线性插值法
bilinear插值法具体程序:
I=imread('flower.jpg'); %读入原图像
[nrows,ncols]=size(I); %读取图像矩阵大小,方便后面操作
K = str2double(inputdlg('please input scale factor (must between 0.2 - 5.0)', 'INPUT scale factor', 1, {'0.5'}));
width = K * nrows;
height = K * ncols;
J = uint8(zeros(width,height));
widthScale = nrows/width;
heightScale = ncols/height;
for x = 5:width - 5 % 5是为了防止矩阵超出边界溢出
for y = 5:height - 5
xx = x * widthScale; % xx, yy为原坐标,x,y为新坐标
yy = y * heightScale;
if (xx/double(uint16(xx)) == 1.0) & (yy/double(uint16(yy)) == 1.0)
J(x,y) = I(int16(xx),int16(yy));%若xx,yy为整数,直接赋值
else
a = double(uint16(xx));
b = double(uint16(yy));
x11 = double(I(a,b)); % x11 <- I(a,b)
x12 = double(I(a,b+1)); % x12 <- I(a,b+1)
x21 = double(I(a+1,b)); % x21 <- I(a+1,b)
x22 = double(I(a+1,b+1)); % x22 <- I(a+1,b+1)
J(x,y) = uint8( (b+1-yy) * ((xx-a)*x21 + (a+1-xx)*x11) + (yy-b) * ((xx-a)*x22 +(a+1-xx) * x12) ); % 用双线性插值计算公式计算
end
end
end
imshow(I);
figure;
imshow(J);