代码实现
1)基于像素采样的图像缩小方法:
% function [im] = resize(I,kr,kc)
% I = imread('img\han.jpg');
% [im1] = dip(I,0.3,0.5);
function [im] = dip(I,kr,kc)
[m,n,d] = size(I); % 得到原始图像尺寸
m2 = round(kr*m); % round函数:四舍五入
n2 = round(kc*n); % 得到新图像尺寸:m2 n2
c1 = 1/kr; c2 = 1/kc;
J = zeros(m2,n2,d); % 初始化新图像矩阵J
for i=1:m2
for j=1:n2
% 计算新图对应原图的x,y坐标--缩小
x = round(c1*i);
y = round(c2*j);
% 检查对应坐标边界条件
if x>m
x = m;
end
if y>n
y = n;
end
if x<1
x = 1;
end
if y<1
y = 1;
end
J(i,j,:) = I(x,y,:);
end
end
im = uint8(J);
figure,imshow(I);title('原图');
figure,imshow(im);title('基于像素采样缩小后的图像');
end
2)基于局部均值的图像缩小方法:
% function [im] = resize(I,kr,kc)
% I = imread('img\han.jpg');
% [im] = dip(I,0.3,0.5);
function [im] = dip(I,kr,kc)
[m,n,d] = size(I); % 得到原始图像尺寸
m2 = round(kr*m);
n2 = round(kc*n); % 得到新图像尺寸:m2 n2
J = zeros(m2,n2,d); % 初始化新图像矩阵J
a = 1/kr; b=1/kc; % 采样间隔
for i=1:m2
for j=1:n2
% 计算新图对应原图的x,y坐标
x1 = round(a*(i-1)+1); % 起始行
x2 = round(a*i); % 结束行
% 检查对应坐标边界条件
if x2>m
x2 = m;
end
y1 = round(b*(j-1)+1); % 起始行
y2 = round(b*j); % 结束行
if y2>n
y2 = n;
end
F = I(x1:x2,y1:y2,:);
% 彩色图像--对每个颜色通道分别求均值
if(d>1)
J(i,j,1) = mean(mean(F(:,:,1))); % mean:数组的均值
J(i,j,2) = mean(mean(F(:,:,2)));
J(i,j,3) = mean(mean(F(:,:,3)));
else
J(i,j,1) = mean(mean(F(:,:,1))); % 灰度图
end
end
end
im = uint8(J);
figure,imshow(I);title('原图');
figure,imshow(im);title('基于局部均值缩小后的图像');
end
命令行窗口输入如下代码:
I = imread('img\han.jpg');
[im1] = dip(I,0.3,0.5);