map1=imread('p.jpg');
[row,col,dep]=size(map1); %行,列,深度值
map=zeros(row,col);
map=uint8(map);
pixsum=row*col; %像素总数
%灰度化
for i=1:row
for j=1:col
gray=0.11*map1(i,j,1)+0.59*map1(i,j,2)+0.3*map1(i,j,3);
map(i,j)=gray;
end
end
%灰度化完成,输出灰度图
figure(1)
imshow(map)
title('原始灰度图像')
%统计各灰度值像素个数,存储在p中,计算概率,存储在pi中
p=zeros(1,256);
pr=zeros(1,256);
sumpr=zeros(1,256); %累积概率密度
for k=1:256;
p(k)=length(find(map==k));
pr(k)=p(k)/pixsum;
end
sumpr(1)=pr(1);
for i=1:255
sumpr(i+1)=sumpr(i)+pr(i);
end
%统计完成,概率计算完成,累积概率密度计算完成。
%绘制灰度直方图
figure(2)
bar(0:255,pr,'g')
axis([0 255 0 max(pr)])
xlabel('灰度r')
ylabel('概率pi')
title('灰度直方图')
%灰度直方图绘制完成
%直方图拉伸。(g-0)/(f-min)=(255-0)/(max-min)
A=max(max(map));
B=min(min(map));
for i=1:row
for j=1:col
%fig(i,j)=255/(A-B)*(map(i,j)-B);
fig(i,j)=255*sumpr(map(i,j)+1);%直方图均衡化
end
end
fig=uint8(fig);
for k=1:256;
pfig(k)=length(find(fig==k));
pfigi(k)=pfig(k)/pixsum;
end
figure(3)
imshow(fig)
title('直方图拉伸后灰度图像')
figure(4)
bar(0:255,pfigi,'g')
axis([0 255 0 max(pfigi)])
xlabel('灰度r')
ylabel('概率pi')
title('直方图拉伸化后灰度直方图')
%计算拉伸前后方差
mean_map=sum(sum(map))/(row*col);
mean_fig=sum(sum(fig))/(row*col);
var_map=sum(sum((map-mean_map).^2))/(row*col);
var_fig=sum(sum((fig-mean_fig).^2))/(row*col);
fprintf('拉伸前方差为:%d',var_map)
fprintf('\n拉伸后方差为:%d\n',var_fig)