Watershed not segmenting correctly
Hi,
I am trying to implement a watershed segmentation to separate touching blobs. I want to separate the blobs from each other but I am getting a separation of the blobs from each other and from the background. In my final segmented image, each blob has a halo like this, instead of just being an isolated blob:
Original Image:
Segmented image:
What am I doing wrong?
Here is the code I am using:
System::Void Watershed(Mat DAPI, Mat DAPIBin, int Param)
{
imwrite("Bin.tif", DAPIBin);
Mat dist_8u;
Mat dist(DAPIBin.size(), CV_32F);
if (Param > 0)
{
distanceTransform(DAPIBin, dist, CV_DIST_L2, CV_DIST_MASK_PRECISE);
dist_8u = (dist > Param);
}
imwrite("dist_8u.tif", dist_8u);
// Find total markers
std::vector<std::vector<cv::Point> > contours;
cv::findContours(dist_8u, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
//Total objects
int ncomp = (int) contours.size();
Mat markers = cv::Mat::zeros(dist.size(), CV_32SC1);
Mat in[] = {dist_8u,dist_8u,dist_8u};
Mat D3ch;
cv::merge(in, 3, D3ch);
for (int i = 0; i < ncomp; i++)
{
drawContours(markers, contours, i, cv::Scalar::all(i + 1), -1);
}
imwrite("Markers.tif", markers);
cv::watershed(D3ch, markers);
Mat Mask=markers>0;
erode(Mask,Mask,Mat());
imwrite("mask.tif", Mask);
if (ncomp > 0)
DAPIBin=DAPIBin.mul(Mask);
imwrite("Final.tif", DAPIBin);
}
And the intermediate images:
guy
Edit: Some more info:
Here is a side by side view of the Markers image before and after the watershed.
After the watershed, the last marker (the one cropped by the top of the image, and which was marker #ncomp) has expanded to fill all area not taken up by other markers. The black outlines in the post-watershed image follow the contours of the pre-watershed markers exactly.
guy