Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

OpenCV Error: Assertion failed in watershed

cv::Mat image;
UIImageToMat(input, image, false);
cv::Mat binary;
cv::cvtColor(image, binary, COLOR_BGR2GRAY);
cv::threshold(binary, binary, 100, 255, THRESH_BINARY);

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

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

    // Create markers image
markers= fg+bg;
    // Create watershed segmentation object
WatershedSegmenter segmenter;
segmenter.setMarkers(markers);

cv::Mat result = segmenter.process(image);
result.convertTo(result,CV_8U);
return MatToUIImage(result);

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

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

While learning about OpenCV I came across the topic of segmentation, and found a thread here. I tried my hand at the provided answer and got the following error,

OpenCV Error: Assertion failed (src.type() == CV_8UC3 && dst.type() == CV_32SC1) in watershed, file /Users/siva/working/opencv/modules/imgproc/src/segmentation.cpp, line 147

And couldn't figure out a solution as I'm new to this topic. Any suggestions/solutions please?