Ask Your Question

# How to find local minima for watershed in OpenCV ?

Watershed has 3 steps

• find gradient map
• locate local minima
• grow seed from minima

Matlab does all this automatically. Not so sure which part OpenCV does. But how do I find local minima from a gradient map for watershed ? minMaxLoc finds the global.

edit retag close merge delete

## 1 answer

Sort by ยป oldest newest most voted
//find local minima by comparing magnitude_eroded with magnitude
cv::Mat magnitude_eroded, markers = cv::Mat::zeros(cv::Size(magnitude.cols, magnitude.rows), CV_8UC1);
cv::erode(magnitude, magnitude_eroded, cv::getStructuringElement(cv::MORPH_RECT, cv::Size(5, 5)));

for(int row = 0; row < magnitude_eroded.rows; row++)
for (int col = 0; col < magnitude_eroded.cols; col++)
{
float diff = abs(magnitude_eroded.at<float>(row, col) - magnitude.at<float>(row, col));
if (diff == 0)
{
markers.at<uchar>(row, col) = 255;
}
}

//compute watershed transformation
cv::Mat seeds = cv::Mat::zeros(cv::Size(image_bgr.cols, image_bgr.rows), CV_32S);
cv::connectedComponents(markers, seeds, 8, CV_32S);
cv::watershed(image_bgr, seeds);

//get border map (need to convert to 3 channel for multiplcation with image)
cv::Mat borders;
seeds.convertTo(seeds, CV_32FC1);                       // threshold only accepts 8bit or 32bit floating
cv::threshold(seeds, borders, 0, 1, cv::THRESH_BINARY); // set all values above 0 to 1 and all below 0 to 0
borders.convertTo(borders, CV_8UC1);                        // convert to 8bit (grayscale)
cv::cvtColor(borders, borders, CV_GRAY2BGR);                // convert to color

//get image with borders
cv::Mat image_with_borders;
cv::multiply(borders, image_bgr, image_with_borders);

cv::imshow("im", image_with_borders); cv::waitKey(0);

more

## Stats

Asked: 2017-01-26 22:06:01 -0500

Seen: 314 times

Last updated: Jan 27 '17