实验内容
给定灰度图像矩阵I(测试示例I=[1 3 9 9; 2 1 3 7; 3 6 0 6; 6 8 2 0])。计算I的对比度。
源码实现
function [res] = Computers(G)
res = 0;
[m,n] = size(G);
Lc = 4*(n-2)*(m-2)+2*(m-2)*3+2*(n-2)*3+4*2; % 算出底数
% 使用全负一矩阵进行包围
a= ones(n+2,m+2);
a=-a;
for i =2:n+1
for j= 2:m+1
a(i,j)=G(i-1,j-1);
end
end
% 4近邻的四个方向。
dir = [1,0;0,1;0,-1;-1,0];
for i= 2:n+1
for j= 2:m+1
for k=1:4
% 相邻位置的坐标x,y
x=i+dir(k,1);
y = j+dir(k,2);
cnt = a(x,y);%新坐标值
if(cnt~=-1)%判断是否越界
res = res +(cnt-a(i,j))*(cnt-a(i,j));
end
end
end
end
res = res/Lc;
分析
这里采用矩阵包围的方法,省去了边角界特殊判断的过程,增强了代码可读性理解性,但是也牺牲一定的性能。有利有弊吧。
结果
ans = 13.3333