Image segmentation using K means
When I execute the following command in Matlab 2012a
centroids=kmeans(imread('image.jpg'),4);
I am getting the following error:
Error using +
Integers can only be combined with integers of the same class, or scalar doubles.
Error in kmeans>distfun (line 659)
D(:,i) = D(:,i) + (X(:,j) - C(i,j)).^2;
Error in kmeans (line 273)
D = distfun(X, C, distance, 0, rep, reps);
I need to segment an image into 4 clusters. The image is an image of a brain tumor in a brain format JPEG
. The size of this image 233x216
.
Please give me a solution to group this image file.
+1
source to share
2 answers
Color image (MxNx3) may be causing the problem
If you want to copy the intensity values ββof an image into 4 clusters, you must do
im = imread('image.jpg');
im=rgb2gray(im) //if you only want grayscale intensities
[idx centroids]=kmeans(double(im(:)),4);
If you want to consider a color, you can do something like
im = imread('image.jpg'); im = reshape(im,size(im,1)*size(im,2),size(im,3)) [idx centroids]=kmeans(double(im(:)),4);
To visualize segmentation, you can do something like
imseg = zeros(size(im,1),size(im,2));
for i=1:max(idx)
imseg(idx==i)=i;
end
imagesc(imseg)
+4
source to share