user1994657
user1994657

Reputation: 117

Image Segmentation Using K means

When I execute the following command in Matlab 2012a

centroids=kmeans(imread('image.jpg'),4);

I get 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 the image into 4 clusters. The image is a CT Brain tumour image in JPEG format. The size of this image is 233x216.
Please give me a solution to cluster this image file.

Upvotes: 1

Views: 13929

Answers (2)

user1994657
user1994657

Reputation: 117

Use the kmeans Segmentation algorithm instead of the default kmeans algorithm provided in MATLAB.

Refer to this file. This is the K means algorithm used for segmentation purpose. By using this algorithm my program is working.

Upvotes: 4

kamjagin
kamjagin

Reputation: 3654

The issue could be due to a colour image (MxNx3)

If what you want to do is to cluster the intensity values in the image into 4 clusters you should rather 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 colour you could 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 the segmentation you could do something like

imseg = zeros(size(im,1),size(im,2));
for i=1:max(idx)
    imseg(idx==i)=i;
end
imagesc(imseg)

Upvotes: 4

Related Questions