Ask Your Question

How to apply K means in a mask of an image instead the whole one

asked 2015-03-13 11:43:27 -0500

rafafirenze gravatar image


I want to apply a K Means to a region of an image not squared or a rectangle. For example the source image is:

image description

now I select a custom mask:

image description

and apply K Means with k = 3:

image description

Obviously without considering the bounds (white).

Instead, what I can do with OpenCV is K Means but considering the bounds:

image description

And that messes out my final image because black is considered one colour.

Do you have any clue? Thank you in advance.

edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted

answered 2015-03-13 13:24:22 -0500

Guanta gravatar image

updated 2015-03-13 13:25:43 -0500

A quick and dirty solution (maybe s.o. else knows sth more elegant):

// assume you loaded img as color-image
// and that mask is 0 in the areas which you don't want
std::vector<cv::Vec3b> points;
for( int y = 0; y < img.rows; y++){
    for( int x = 0; x < img.rows; x++){
        if ( mask(y,x) != 0 ) 

// now run kmeans using the points as input-data

as soon as you have the labels you can go through your image as above and set the image according to the label.

edit flag offensive delete link more

answered 2015-03-13 13:39:43 -0500

matman gravatar image

updated 2015-03-13 13:41:44 -0500

It looks like you execute kmeans on the whole image. Take a look at: Interactive foreground extraction using grab cut algortihm

Then you can use the result image as mask for src.copyTo(dst, mask); and then execute kmeans. This should work, because copied pixels are those wich are unequal to zero in mask image. But I didn't test it.

edit flag offensive delete link more



I thought rafafurenze already has the mask, but if not grabcut or watershed might be used to create them. However, if he uses then copyTo() he will run in the same problem as before since dst will be 0 outside the mask -> kmeans will be trained on these pixels too. See a solution in my answer for that issue.

Guanta gravatar imageGuanta ( 2015-03-14 06:20:37 -0500 )edit

Question Tools

1 follower


Asked: 2015-03-13 11:43:27 -0500

Seen: 1,834 times

Last updated: Mar 13 '15