在opencv中分别检测两个相交的矩形

Detect two intersecting rectangles separately in opencv

我可以检测到彼此分开的矩形。但是,我在接触矩形时遇到问题,如下所示:

Two rectangles in contact

我应该检测图像中的 2 个矩形。我正在按预期使用 findContours,并且尝试了各种 modes:CV_RETR_TREE、CV_RETR_LIST。我总是得到最外面的单个轮廓,如下所示:

Outermost contour detected

我尝试过使用或不使用 canny 边缘检测。我所做的如下:

cv::Mat element = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3,3));
cv::erode(__mat,__mat, element);
cv::dilate(__mat,__mat, element);

// Find contours
std::vector<std::vector<cv::Point> > contours;
cv::Mat coloredMat;
cv::cvtColor(__mat, coloredMat, cv::COLOR_GRAY2BGR);
int thresh = 100;
cv::Mat canny_output;
cv::Canny( __mat, canny_output, thresh, thresh*2, 3 );

cv::findContours(canny_output, contours, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE);

如何分别检测两个矩形?

如果你已经知道矩形的尺寸,你可以使用generalizedHoughTransform

如果不知道矩形的尺寸,可以使用distanceTransform。局部最大值将为您提供中心位置以及从中心到最近边缘的距离(等于矩形短边的一半)。进一步处理角点检测/分水岭,您应该能够找到方向和尺寸(尽管如果两个矩形相互重叠很多,此方法可能会失败)

简单的角点检测和强力搜索(只需尝试给定角点的所有可能的矩形组合,看看哪个与图像最匹配,请注意,仅给定 3 个点即可定义矩形)也可能有效