What does this means ?

Illustration
Ynne - 2023-02-21T11:34:42+00:00
Question: What does this means ?

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 ?

Expert Answer

Profile picture of Neeta Dsouza Neeta Dsouza answered . 2025-11-20

The range between 0 and 255 is divided into 8 ranges by default. They are 0-31, 32- 63, 64-95, etc. As you can see all of your elements are in the second range, except for the one with the value 31. The count is the number of times a number in one range occurs horizontally adjacent to another in another range. You have 19 pairs where the side-by-side pixels are both in range 2, and only one pairing, when it's looking at the very lower right, where there is a pairing between a number in range 2 (33) and a number in range 1 (31). I know it can be kind of tricky, so do you understand that explanation?
 
You can adjust the window size and the range size. You can have a 256 by 256 array if you want. See my demo.
% 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')


 


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!