Azzera filtri
Azzera filtri

color segmentation on a user-selected image using k-means clustering to identify and display different color classes, and visualizes the results with pie charts.

6 visualizzazioni (ultimi 30 giorni)
Hello all,
I hope you are doing well.
I need your help in adjusting this code to capture only the porosity (black shapes) that exists in the original image, instead of the inaccurate percentage results shown in the produced image and the pie chart.
I greatly appreciate your consideration.
Here is the code
% Do color segmentation by kmeans classification.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 16;
% Check that user has the Image Processing Toolbox installed and licensed.
hasLicenseForToolbox = license('test', 'image_toolbox');
if ~hasLicenseForToolbox
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')
return;
end
end
% Check that user has the Statistics and Machine Learning Toolbox installed and licensed.
hasLicenseForToolbox = license('test', 'Statistics_toolbox');
if ~hasLicenseForToolbox
message = sprintf('Sorry, but you do not seem to have the Statistics and Machine Learning Toolbox.\nDo you want to try to continue anyway?');
reply = questdlg(message, 'Toolbox missing', 'Yes', 'No', 'Yes');
if strcmpi(reply, 'No')
return;
end
end
% Load the specific image file
fullFileName = 'D:\\OneDrive - York University\\Zeiss Microscope\\Dogbone TPU\Downwards\\Downwards TPU Traditional Direction.jpg';
% fullFileName = 'D:\\OneDrive - York University\\Zeiss Microscope\\image J\\Downwards\\two\\Image Downwards.png';
if ~exist(fullFileName, 'file')
errorMessage = sprintf('Error: %s does not exist.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
rgbImage = imread(fullFileName);
% Get the dimensions of the image. numberOfColorChannels should be = 3.
[rows, columns, numberOfColorChannels] = size(rgbImage);
if numberOfColorChannels ~= 3
message = sprintf('You need to select an RGB image.');
uiwait(errordlg(message));
return;
end
% Display the original color image.
subplot(2, 2, 1);
imshow(rgbImage);
title('Original Color Image', 'FontSize', fontSize);
set(gcf, 'Units', 'Normalized', 'Outerposition', [0, 0, 1, 1]);
% Extract and display the color channels.
redChannel = rgbImage(:, :, 1);
greenChannel = rgbImage(:, :, 2);
blueChannel = rgbImage(:, :, 3);
subplot(2, 2, 2);
imshow(redChannel);
title('Red Channel', 'FontSize', fontSize);
subplot(2, 2, 3);
imshow(greenChannel);
title('Green Channel', 'FontSize', fontSize);
subplot(2, 2, 4);
imshow(blueChannel);
title('Blue Channel', 'FontSize', fontSize);
% Ask user how many color classes they want.
defaultValue = 5;
titleBar = 'Enter an integer value';
userPrompt = 'Enter the number of color classes to find (2 through 6)';
caUserInput = inputdlg(userPrompt, titleBar, 1, {num2str(defaultValue)});
if isempty(caUserInput), return; end % Bail out if they clicked Cancel.
numberOfClasses = round(str2double(caUserInput{1}));
% Prepare data for k-means
imageData = double(reshape(rgbImage, [], 3));
indexes = kmeans(imageData, numberOfClasses);
% Reshape the cluster indexes to the original image dimensions
clusteredImage = reshape(indexes, size(rgbImage, 1), size(rgbImage, 2));
% Display clustered image
figure;
imshow(label2rgb(clusteredImage));
title('Clustered Image', 'FontSize', fontSize);
% Calculate pixel counts for each class for the pie chart
classCounts = histcounts(indexes, 1:numberOfClasses+1);
% Create a custom color map based on the clustered image
uniqueClasses = unique(indexes);
colorsForPie = label2rgb(uniqueClasses); % Convert class numbers to RGB colors
colorsForPie = reshape(colorsForPie, [length(uniqueClasses), 3]); % Ensure it's a Nx3 matrix for RGB
% Generate pie chart
figure;
pie(classCounts, arrayfun(@(x) sprintf('Class %d', x), 1:numberOfClasses, 'UniformOutput', false));
colormap(colorsForPie); % Apply custom colors
% Title for pie chart
title('Pie Chart of Color Classes', 'FontSize', fontSize);

Risposte (1)

Shreeya
Shreeya il 6 Mag 2024
You can perhaps try to improve the K-means clustering result through the elbow method to find the optimal value of K, and check for any performance improvements. The answer linked below can help you with the implementation:

Community Treasure Hunt

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

Start Hunting!

Translated by