MATLAB Answers

K-means segmentation

10 views (last 30 days)
Hello. I have a grayscale image with a mole and skin which I want to segment with K-means algorithm.I want the mole pixels to be classified in class 1 and the skin pixels to be classified in class2. How can I do that? The code above works, but sometimes the mole is black and sometimes is white. I want this to be done with k-means segmentation, I know it can be done in other different ways. Thank you!

  0 Comments

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 15 Apr 2020
The class numbers that kmeans() assigns can vary from one run to the next because it uses random numbers. However you can renumber the class labels if you know something about the class, like you always want class 1 to be the darker class, and class 2 to be the lighter class. See attached demo.

  0 Comments

Sign in to comment.

More Answers (1)

Rajani Mishra
Rajani Mishra on 15 Apr 2020
You can use function "imsegkmeans()" to perform K-means based image segmentation. I have used this function to segment your image into two classes. Below is the result :
Directly using imsegkmeans() function will result to misplaced results so improve the k-means segmentation by supplementing the information about each pixel. Below is the code used to generate above result:
RGB = imread('image.png');
wavelength = 2.^(0:5) * 3;
orientation = 0:45:135;
g = gabor(wavelength,orientation);
I = rgb2gray(im2single(RGB));
gabormag = imgaborfilt(I,g);
montage(gabormag,'Size',[4 6])
for i = 1:length(g)
sigma = 0.5*g(i).Wavelength;
gabormag(:,:,i) = imgaussfilt(gabormag(:,:,i),3*sigma);
end
montage(gabormag,'Size',[4 6])
nrows = size(RGB,1);
ncols = size(RGB,2);
[X,Y] = meshgrid(1:ncols,1:nrows);
featureSet = cat(3,I,gabormag,X,Y);
L2 = imsegkmeans(featureSet,2,'NormalizeInput',true);
C = labeloverlay(RGB,L2);
imshow(C)
Above Code is taken from the example section of imsegkmeans function documentation page. For reading more about the function or understanding the code refer below for its link:
Hope this helps!

  0 Comments

Sign in to comment.


Translated by