How to classification use the KNN method with GLCM Ektraction?

3 次查看(过去 30 天)
How to calculate energy, contrast homogen and correlation used GLCM ektraction and classification use the KNN method?

回答(1 个)

Gayathri
Gayathri 2025-6-13
编辑:Gayathri 2025-6-13
To calculate energy, contrast, homogeneity and correlation we can take the help of "graycomatrix" and "graycoprops" functions in MATLAB. Now the features extracted using these functions could be given as input to the "fitcknn" function to train a k-nearest neighbour classification. Please refer to the code below to achieve the same.
% Replace with your dataset path
dataPath = "folder_path"; % Update with your dataset path
imds = imageDatastore(dataPath, ...
'IncludeSubfolders', true, ...
'LabelSource', 'foldernames', ...
'FileExtensions', {'.png', '.jpg'});
% Split dataset into training (70%) and testing (30%)
[imdsTrain, imdsTest] = splitEachLabel(imds, 0.7, 'randomized');
disp(['Number of training images: ', num2str(numel(imdsTrain.Files))]);
disp(['Number of testing images: ', num2str(numel(imdsTest.Files))]);
% Function to extract GLCM features (defined below)
trainFeatures = extractGLCMFeatures(imdsTrain);
testFeatures = extractGLCMFeatures(imdsTest);
% Get labels
trainLabels = imdsTrain.Labels;
testLabels = imdsTest.Labels;
% Create KNN model (k=5 neighbors)
knnModel = fitcknn(trainFeatures, trainLabels, ...
'NumNeighbors', 5, ...
'Distance', 'euclidean', ...
'Standardize', true); % Standardize features for better performance
% Predict on test set
predictedLabels = predict(knnModel, testFeatures);
% Compute accuracy
accuracy = mean(predictedLabels == testLabels);
fprintf('Test accuracy: %.2f%%\n', accuracy * 100);
% Function to extract GLCM features from an imageDatastore
function features = extractGLCMFeatures(imds)
numImages = numel(imds.Files);
features = zeros(numImages, 4); % 4 features: contrast, correlation, energy, homogeneity
for i = 1:numImages
img = readimage(imds, i);
% Extract GLCM features for the image
features(i, :) = computeGLCMFeatures(img);
end
end
% Function to compute GLCM features for a single image
function glcmFeatures = computeGLCMFeatures(img)
% Convert to grayscale if RGB
if size(img, 3) == 3
img = rgb2gray(img);
end
% Define offsets: [distance angle] for 0°, 45°, 90°, 135°
offsets = [0 1; -1 1; -1 0; -1 -1];
% Compute GLCM
glcm = graycomatrix(img, 'Offset', offsets,'Symmetric', true);
% Compute GLCM features
stats = graycoprops(glcm, {'Contrast', 'Correlation', 'Energy', 'Homogeneity'});
glcmFeatures = [
mean(stats.Contrast) ...
mean(stats.Correlation) ...
mean(stats.Energy) ...
mean(stats.Homogeneity)
];
end
For more information on different functions used in the code above, please refer to the documentation links given below:

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by