正在参与的工程里有一个小功能是求两个矩形之间的最小距离。大致翻了一下 OpenCV,貌似没看到现成的函数,那就自己写一个好了。

    一个画面中,两个矩形的几何关系大致可分为如下几种,以 C1 为参考,分别是:

    (1) 不相交,但在 X 或 Y 轴方向上有部分重合坐标,比如矩形 1 和 2,此时,最小距离为两个矩形之间的最小平行距离或垂直距离,如图中红色箭线 D12 所示。

    (2) 不相交,在 X 和 Y 轴方向上均无重合坐标,比如矩形 1 和 3,此时最小距离为两矩形距离最近的两个顶点之间的距离,如图中红色箭线 D13。

    (3) 相交,此时距离为负数,如矩形 1 和 4。

    (14条消息) 求两个矩形之间的最小距离_牧羊女-CSDN博客 - 图1

    为了实现以上几何关系,写了个小函数:

    1. int min_distance_of_rectangles(Rect rect1, Rect rect2) C1.x = rect1.x + (rect1.width / 2); C1.y = rect1.y + (rect1.height / 2); C2.x = rect2.x + (rect2.width / 2); C2.y = rect2.y + (rect2.height / 2);if((Dx < ((rect1.width + rect2.width)/ 2)) && (Dy >= ((rect1.height + rect2.height) / 2))) min_dist = Dy - ((rect1.height + rect2.height) / 2);else if((Dx >= ((rect1.width + rect2.width)/ 2)) && (Dy < ((rect1.height + rect2.height) / 2))) min_dist = Dx - ((rect1.width + rect2.width)/ 2);else if((Dx >= ((rect1.width + rect2.width)/ 2)) && (Dy >= ((rect1.height + rect2.height) / 2)))int delta_x = Dx - ((rect1.width + rect2.width)/ 2);int delta_y = Dy - ((rect1.height + rect2.height)/ 2); min_dist = sqrt(delta_x * delta_x + delta_y * delta_y);

    测试一下:

    #include "opencv2/core/core.hpp"#include "opencv2/highgui/highgui.hpp"#include "opencv2/imgproc/imgproc.hpp"Mat img(Size(1000, 1000), CV_8UC3, Scalar(255, 255, 255));Rect rect1(200,200,300,300);Rect rect2(600,100,300,200);Rect rect3(700,600,100,100);Rect rect4(100,400,200,200);    rectangle(img, rect1, Scalar(255, 0, 0), -1);    rectangle(img, rect2, Scalar(0, 255, 0), -1);    rectangle(img, rect3, Scalar(0, 0, 255), -1);    rectangle(img, rect4, Scalar(0, 255, 255), -1);    imwrite("rects.bmp", img);int min_dist_12 = min_distance_of_rectangles(rect1, rect2);int min_dist_13 = min_distance_of_rectangles(rect1, rect3);int min_dist_14 = min_distance_of_rectangles(rect1, rect4);cout << "Minimun distance between rect1 and rect2 is: " << min_dist_12 << endl;cout << "Minimun distance between rect1 and rect3 is: " << min_dist_13 << endl;cout << "Minimun distance between rect1 and rect4 is: " << min_dist_14 << endl;
    

    绘制的实验图像:

    (14条消息) 求两个矩形之间的最小距离_牧羊女-CSDN博客 - 图2

    最小距离计算执行结果如下,与预期的结果相同。

    (14条消息) 求两个矩形之间的最小距离_牧羊女-CSDN博客 - 图3 https://blog.csdn.net/DeliaPu/article/details/104837064 ```