Dear all, I picked up a window of 5X5 from a given image im1=im(1:5,1:5) ans = 41 40 38 38 37 42 40 38 37 35 43 41 38 37 34 43 41 37 35 33 42 40 36 33 31 then I used graycomatrix to calculate the glcm matrix as following: glcm=graycomatrix(im1) glcm = 0 0 0 0 0 0 0 0 1 19 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 My questions are: why the result matrix is 8*8 ? how can we get the number of gray levels of an image ? How can i interpret the values 1 and 19 in the glcm matrix ?
Neeta Dsouza answered .
2025-11-20
% Finds and displays the GLCM of a user chosen gray scale image.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear all; % Erase all existing variables.
workspace; % Make sure the workspace panel is showing.
fontSize = 18;
% Change the current folder to the folder of this m-file.
% (The line of code below is from Brett Shoelson of The Mathworks.)
if(~isdeployed)
cd(fileparts(which(mfilename)));
end
% Check that user has the Image Processing Toolbox installed.
hasIPT = license('test', 'image_toolbox');
if ~hasIPT
% User does not have the toolbox installed.
message = sprintf('Sorry, but you do not seem to have the Image Processing Toolbox.\nDo you want to try to continue anyway?');
reply = questdlg(message, 'Toolbox missing', 'Yes', 'No', 'Yes');
if strcmpi(reply, 'No')
% User said No, so exit.
return;
end
end
% Read in a standard MATLAB gray scale demo image.
%===============================================================================
% Get the name of the demo image the user wants to use.
% Let's let the user select from a list of all the demo images that ship with the Image Processing Toolbox.
folder = fileparts(which('cameraman.tif')); % Determine where demo folder is (works with all versions).
% Demo images have extensions of TIF, PNG, and JPG. Get a list of all of them.
imageFiles = [dir(fullfile(folder,'*.TIF')); dir(fullfile(folder,'*.PNG')); dir(fullfile(folder,'*.jpg'))];
for k = 1 : length(imageFiles)
% fprintf('%d: %s\n', k, files(k).name);
[~, baseFileName, extension] = fileparts(imageFiles(k).name);
ca{k} = [baseFileName, extension];
end
% Sort the base file names alphabetically.
[ca, sortOrder] = sort(ca);
imageFiles = imageFiles(sortOrder);
button = menu('Use which gray scale demo image?', ca); % Display all image file names in a popup menu.
% Get the base filename.
baseFileName = imageFiles(button).name; % Assign the one on the button that they clicked on.
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~exist(fullFileName, 'file')
% File doesn't exist -- didn't find it there. Check the search path for it.
fullFileNameOnSearchPath = baseFileName; % No path this time.
if ~exist(fullFileNameOnSearchPath, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
grayImage = imread(fullFileName);
% Get the dimensions of the image.
% numberOfColorBands should be = 1.
[rows, columns, numberOfColorBands] = size(grayImage);
if numberOfColorBands > 1
% It's not really gray scale like we expected - it's color.
% Convert it to gray scale by taking a weighted average of the individual color channels.
grayImage = rgb2gray(grayImage);
end
% Display the original gray scale image.
subplot(2, 3, 1);
imshow(grayImage, []);
colorbar
axis on;
title('Original Grayscale Image', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
% Let's compute and display the histogram.
[pixelCount, grayLevels] = imhist(grayImage);
subplot(2, 3, 2);
bar(grayLevels, pixelCount, 'BarWidth', 1, 'EdgeColor', 'none');
grid on;
title('Histogram of original image', 'FontSize', fontSize);
xlim([0 grayLevels(end)]); % Scale x axis manually.
drawnow;
% Ask user for a number of gray level ranges to use.
defaultValue = 256;
titleBar = 'Enter a value';
userPrompt = 'Enter the number of gray level ranges (2 to 256)';
caUserInput = inputdlg(userPrompt, titleBar, 1, {num2str(defaultValue)});
if isempty(caUserInput),return,end; % Bail out if they clicked Cancel.
% Round to nearest integer in case they entered a floating point number.
integerValue = round(str2double(cell2mat(caUserInput)));
% Check for a valid integer.
if isnan(integerValue)
% They didn't enter a number.
% They clicked Cancel, or entered a character, symbols, or something else not allowed.
integerValue = defaultValue;
message = sprintf('I said it had to be an integer.\nI will use %d and continue.', integerValue);
uiwait(warndlg(message));
end
numGLRanges = integerValue; % Rename it for readability.
% Ask user for the distance to use.
defaultValue = 1;
titleBar = 'Enter a value';
userPrompt = 'Enter the distance away to look (typically 1)';
caUserInput = inputdlg(userPrompt, titleBar, 1, {num2str(defaultValue)});
if isempty(caUserInput),return,end; % Bail out if they clicked Cancel.
% Round to nearest integer in case they entered a floating point number.
D = round(str2double(cell2mat(caUserInput)));
% Check for a valid integer.
if isnan(D)
% They didn't enter a number.
% They clicked Cancel, or entered a character, symbols, or something else not allowed.
D = defaultValue;
message = sprintf('I said it had to be an integer.\nI will use %d and continue.', D);
uiwait(warndlg(message));
end
% Now get the GLCM with graycomatrix().
directionsToLook = [0, D; -D, D; -D, 0; -D, -D];
glcm = graycomatrix(grayImage, ...
'NumLevels', numGLRanges,...
'offset', directionsToLook);
fprintf('The range of glcm values is %d to %d.\nNote: The units of GLCM are "pixels" since it is a count of occurrences of gray level pairs.\n', min(glcm(:)), max(glcm(:)));
numberOfDirections = size(glcm, 3);
for k = 1 : numberOfDirections
subplot(2, 3, k+2);
thisGLCM = glcm(:, :, k);
imshow(thisGLCM, []);
axis on;
caption = sprintf('GLCM for direction %d', k);
title(caption, 'FontSize', fontSize);
% Apply a colormap
cmap = jet(max(thisGLCM(:)));
cmap(1,:) = 0;
colormap(gca, cmap);
% thisGLCM % Display in the command window.
end
% Combine all directions into one.
% Sum along the third dimension.
glcm = sum(glcm, 3);
% Display the 2D glcm as a matrix.
figure;
% Create a colormap
maxValue = max(glcm(:));
cmap = jet(maxValue);
cmap(1,:) = 0;
% Convert to an RGB image, in case they want to save it.
rgbImage = ind2rgb(glcm, cmap);
imshow(rgbImage);
% imshow(glcm, []);
axis on;
title('Image of all the directions of the GLCM', 'FontSize', fontSize);
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
% Get rid of tool bar and pulldown menus that are along top of figure.
set(gcf, 'Toolbar', 'none', 'Menu', 'none');
% Give a name to the title bar.
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')