相交矩形的坐标由两矩形在x、y方向重叠区间的边界决定:intersect_left = max(r1.left, r2.left),intersect_right = min(r1.right, r2.right),intersect_top = max(r1.top, r2.top),intersect_bottom = min(r1.bottom, r2.bottom);若left≥right或top≥bottom则无相交,面积为0。

相交矩形的坐标怎么算?
两个轴对齐矩形(即边与坐标轴平行)的相交区域,本质是求它们在 x 和 y 两个方向上重叠区间的交集。关键不是“有没有相交”,而是“相交部分的左、右、上、下边界在哪”。
设矩形用 left、right、top、bottom 表示(注意:这里 top 是较小 y 值,bottom 是较大 y 值,即 y 轴向下为正;若用 y + height 表示,则需先转换)。
intersect_left = max(rect1.left, rect2.left)intersect_right = min(rect1.right, rect2.right)intersect_top = max(rect1.top, rect2.top)intersect_bottom = min(rect1.bottom, rect2.bottom)
如果 intersect_left >= intersect_right 或 intersect_top >= intersect_bottom,说明无相交,面积为 0。
用 C++ 写个安全的相交面积函数
直接返回面积更常用,但必须处理无交集情况,避免负数或溢出。推荐用 long long 防止 int 溢出(尤其坐标值较大时)。
int computeIntersectionArea(const Rect& a, const Rect& b) {
int left = std::max(a.left, b.left);
int right = std::min(a.right, b.right);
int top = std::max(a.top, b.top);
int bottom = std::min(a.bottom, b.bottom);
if (left >= right || top >= bottom) return 0;
return (right - left) * (bottom - top);
}
注意:Rect 结构体需确保 right > left 且 bottom > top,否则逻辑失效。若输入可能非法(如宽高为负),应先做归一化。
组合式C++代码评审方案,融合静态分析、AI推理、多轮迭代评审和C++专项检查,适用于PR审查、增量代码审查、全项目评审和代码质量评分,触发词包括review cpp、cpp代码评审、C++review、代码审查。
OpenCV 的 cv::Rect 怎么用?
OpenCV 的 cv::Rect 默认用 x、y(左上角)、width、height,y 向下为正,所以 y 对应 top,y + height 对应 bottom。
- 相交操作直接调用
rect1 & rect2,返回新的cv::Rect - 面积用
rect.area(),内部已处理空矩形(返回 0) - 但要注意:若任一矩形
width 或 <code>height ,<code>&运算结果可能是无效矩形(area()仍返回 0,但x/y可能异常)
稳妥写法:
cv::Rect inter = rect1 & rect2; int area = inter.width > 0 && inter.height > 0 ? inter.area() : 0;
为什么有时候算出来面积是负数?
根本原因只有两个:坐标系理解错,或矩形定义不一致。
- 把
top当成最大 y(比如屏幕坐标系习惯把 top 当 y=0,bottom 当 y=大值),但代码里当成了最小 y —— 导致bottom - top算反 - 用了
cv::Rect(x,y,w,h)却误以为y是 bottom,实际是 top - 手动计算时漏判
left >= right,直接乘了负宽负高
最保险的做法:统一用“左、右、上、下”四边界表示,并在函数入口断言 left 。一旦发现坐标混乱,立刻打日志输出四个值,比猜快得多。
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!










