Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Extracting objects from background with watershed

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