user1030373
user1030373

Reputation: 75

K means clustering and Matlab

I need to use the kmeans function on a rgb image. Each element of the algorithm need to have 3 dimensions, one for each channel of the image. The number of elements will be the total amount of pixels of the image. I need to use kmeans on the cluster #5.

So this is what I tried:

img = imread('mypic.jpg');
red = img(:,:,1);
green = img(:,:,2);
blue = img(:,:,3);

kmeans(red,5)


I dont know if I'm doing it correctly or not. I'm having this error:

??? Error using ==> plus
Integers can only be combined with integers of the same class, or scalar doubles.

Error in ==> kmeans>distfun at 704
            D(:,i) = D(:,i) + (X(:,j) - C(i,j)).^2;

Error in ==> kmeans at 313
    D = distfun(X, C, distance, 0);

Error in ==> mysegmentation at 9
kmeans(R,2)

Can anyone give me a hand? Thanks

Upvotes: 3

Views: 12489

Answers (3)

Nassir
Nassir

Reputation: 1

I1= imread('d:\flowers.jpg');
I2=rgb2gray(I1);

I=double(I2);
figure
subplot(1,3,1)
imshow(I1)
subplot(1,3,2)
imshow(I2)
g=kmeans(I(:),4);
J = reshape(g,size(I));
subplot(1,3,3)
imshow(J,[])

Upvotes: 0

John
John

Reputation: 5905

Your exception, is due to the fact that kmeans is expecting data of type double (Thus the call to double in the second line below). But you have an additional issue, in that you're not passing the proper data into kmeans. You need to create a single numpixels x 3 matrix. reshape is your friend for this stuff. Here's an example. Good luck.

img = imread('mypic.jpg');
flatImg = double(reshape(img,size(img,1)*size(img,2),size(img,3)));
idx = kmeans(flatImg,5);
imagesc(reshape(idx,size(img,1),size(img,2)));

Upvotes: 5

ypnos
ypnos

Reputation: 52317

Try img = double(imread('mypic.jpg'))/255.;

Upvotes: 1

Related Questions