Ask Your Question
0

Extracting objects from background with watershed

asked 2015-10-25 13:07:23 -0500

vitruvius gravatar image

Hello,

I am using following watershed algorithm to isolate my objects from the background. After I get my segmented image, how can I extract my objects from the source image?

#include "opencv2/opencv.hpp"
#include <string>

using namespace cv;
using namespace std;

class WatershedSegmenter{
private:
    Mat markers;
public:
    void setMarkers(Mat& markerImage)
    {
        markerImage.convertTo(markers, CV_32S);
    }

    Mat process(Mat &image)
    {
        watershed(image, markers);
        markers.convertTo(markers, CV_8U);
        return markers;
    }
};


int main(int argc, char* argv[])
{
    Mat src = imread("source.png", 1);
    Mat binary;// = imread(argv[2], 0);
    cvtColor(src, binary, CV_BGR2GRAY);
    threshold(binary, binary, 100, 255, THRESH_BINARY | CV_THRESH_OTSU);

    // Eliminate noise and smaller objects
    Mat fg;
    erode(binary, fg, Mat(), Point(-1, -1), 2);

    // Identify image pixels without objects
    Mat bg;
    dilate(binary, bg, Mat(), Point(-1, -1), 3);
    threshold(bg, bg, 1, 128, THRESH_BINARY_INV);

    // Create markers image
    Mat markers(binary.size(), CV_8U, Scalar(0));
    markers = fg + bg;

    // Create watershed segmentation object
    WatershedSegmenter segmenter;
    segmenter.setMarkers(markers);

    Mat result = segmenter.process(src);
    result.convertTo(result, CV_8U);
    imshow("Result", result);

    waitKey(0);

    return 0;
}

Source image: image description

Watershed result: image description

The result I would like to have: image description

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
2

answered 2015-10-25 13:20:14 -0500

LorenaGdL gravatar image

updated 2015-10-25 13:21:23 -0500

That's pretty easy, just add the following lines to the end of your code:

result = (result > 200);        //binarize image
Mat result2;
src.copyTo(result2, result);    //copy using mask

You'll get this in result2:

image description

edit flag offensive delete link more

Comments

Ah I see. I was trying too complicated stuff. Thanks.

vitruvius gravatar imagevitruvius ( 2015-10-25 13:27:27 -0500 )edit

You're welcome ;)

LorenaGdL gravatar imageLorenaGdL ( 2015-10-25 13:29:11 -0500 )edit
Login/Signup to Answer

Question Tools

1 follower

Stats

Asked: 2015-10-25 13:07:23 -0500

Seen: 423 times

Last updated: Oct 25 '15