流域边界紧密围绕一个区域

时间:2017-02-09 13:01:04

标签: c++ opencv watershed

我试图在OpenCV中平均制作两个blob。为了实现这一点,我计划在以下列方式预处理的图像上使用分水岭算法:

cv::Mat common, diff, processed, result;
cv::bitwise_and(blob1, blob2, common); //calc common area of the two blobs
cv::absdiff(blob1, blob2, diff);       //calc area where they differ

cv::distanceTransform(diff, processed, CV_DIST_L2, 3); //idea here is that the highest intensity 
                                                       //will be in the middle of the differing area
cv::normalize(processed, processed, 0, 255, cv::NORM_MINMAX, CV_8U); //convert floats to bytes

cv::Mat watershedMarkers, watershedOutline;
common.convertTo(watershedMarkers, CV_32S, 1. / 255, 1); //change background to label 1, common area to label 2
watershedMarkers.setTo(0, processed); //set 0 (unknown) for area where blobs differ

cv::cvtColor(processed, processed, CV_GRAY2RGB); //watershed wants 3 channels
cv::watershed(processed, watershedMarkers);
cv::rectangle(watershedMarkers, cv::Rect(0, 0, watershedMarkers.cols, watershedMarkers.rows), 1); //remove the outline

//draw the boundary in red (for debugging)
watershedMarkers.convertTo(watershedOutline, CV_16S);
cv::threshold(watershedOutline, watershedOutline, 0, 255, CV_THRESH_BINARY_INV);
watershedOutline.convertTo(watershedOutline, CV_8U);
processed.setTo(cv::Scalar(CV_RGB(255, 0, 0)), watershedOutline);

//convert computed labels back to mask (blob), less relevant but shows my ultimate goal
watershedMarkers.convertTo(watershedMarkers, CV_8U);
cv::threshold(watershedMarkers, watershedMarkers, 1, 0, CV_THRESH_TOZERO_INV);
cv::bitwise_not(watershedMarkers * 255, result);

我的结果问题是计算的边界(几乎)总是与两个斑点共有的区域相邻。以下是图片:

输入标记(黑色= 0,灰色= 1,白色= 2) Input markers

分水岭输入图像(距离变换结果),结果轮廓用红色绘制: watershed input image with drawn outline

我希望边界沿着输入的最大强度区域(即沿着不同区域的中间)。相反(正如你所看到的)它主要围绕标记为2的区域,稍微移动以触摸背景(标记为1)。我在这里做错了什么,还是我误解了分水岭是如何运作的?

1 个答案:

答案 0 :(得分:1)

从这张图片开始:

enter image description here

只需将全零图像传递给分水岭算法即可获得正确的结果。然后"盆地" 同样充满了" water" 从每个"" (然后只记得删除默认设置为分水岭算法-1的外边框):

enter image description here

代码:

#include <opencv2\opencv.hpp>

using namespace cv;
using namespace std;

int main()
{
    Mat1b img = imread("path_to_image", IMREAD_GRAYSCALE);

    Mat1i markers(img.rows, img.cols, int(0));
    markers.setTo(1, img == 128);
    markers.setTo(2, img == 255);

    Mat3b image(markers.rows, markers.cols, Vec3b(0,0,0));
    markers.convertTo(markers, CV_32S);
    watershed(image, markers);

    Mat3b result;
    cvtColor(img, result, COLOR_GRAY2BGR);
    result.setTo(Scalar(0, 0, 255), markers == -1);

    imshow("Result", result);
    waitKey();

    return(0);
}