# how to calculate glcm ?

6 views (last 30 days)
Oman Wisni on 15 Oct 2018
Commented: Oman Wisni on 17 Oct 2018
Hi, here I have code for calculate glcm using graycoprops(); and manual calculated. When I run in comman window using graycoprops() I get result. But in manual code the result is 0. Any explain and have will good. thanks !
[fname, pathname]=uigetfile({'*.bmp*','Input image'}); fname = fullfile(pathname, fname); im=imread(fname);
[~, foldername, ext] = fileparts(fname);
gray = rgb2gray(im);
%using toolbox
glcm = gray;
stats = graycoprops(glcm);
%manual calculated
S = size(gray, 1);
if any(gray(:))
prob = gray./sum(gray(:));
end
prob_norm = gray ./ sum(gray(:));
u = mean2(prob_norm);
py = sum(prob_norm,1);
px = sum(prob_norm,2);
contr = 0; energ = 0; homom = 0; %corr = 0;
for i = 1:S for j = 1:S
energ = energ + prob_norm(i,j)^2;
contr = contr + prob_norm(i,j).*(i-j)^2;
homom = homom + prob_norm(i,j)/(1+(i-j)^2);
%co = i*j*prob(i,j);
end
end
% Correlation
%ux = mean(px); sx=std(px);
%uy = mean(py); sy=std(py);
%corr =(sum(co(:))-(ux*uy))/(sx*sy);
Stat.Contrast = contr;
Stat.Homogeneity = homom;
Stat.Energy = energ;
%Stat.Correlation = corr;
disp ('========== Fitur Tekstur GLCM ==========')
disp(strcat(['Contrast = ',num2str(contr)]))
disp(strcat(['Homogenitas = ',num2str(homom)]))
disp(strcat(['Energy = ',num2str(energ)]))

Image Analyst on 16 Oct 2018
Oman Wisni on 16 Oct 2018
yes sir I will replay to ask and attached my code. I want calculate GLCM using formula which I get from haralick to know did the result same or not.
I already using graycoprops(); But when I using formula to calculate the result 0.
In below I have an image and my code : S = size(gray, 4);
if any(gray(:))
prob = gray./sum(gray(:));
end
prob_norm = gray ./ sum(gray(:));
u = mean2(prob_norm);
py = sum(prob_norm,1);
px = sum(prob_norm,2);
contr = 0;
energ = 0;
homom = 0;
corr = 0;
for i = 1:S
for j = 1:S
energ = energ + prob_norm(i,j)^2;
contr = contr + prob_norm(i,j).*(i-j)^2;
homom = homom + prob_norm(i,j)/(1+(i-j)^2);
co = i*j*prob(i,j);
end
end
%Correlation
ux = mean(px); sx=std(px);
uy = mean(py); sy=std(py);
corr =(sum(co(:))-(ux*uy))/(sx*sy);
Stat.Contrast = contr;
Stat.Homogeneity = homom;
Stat.Energy = energ;
Stat.Correlation = corr;
Oman Wisni on 17 Oct 2018
Which one I wrong declarad that code? Or my code not complete so the result was 0