Opencv C++ 判断一个点是否在一个矩形内(RECT)
在这里,线上的点也算在矩形内;
如果不算线上的点,将isPointInRect中判断<= 和>= 都改为< 和>;
// A code C++
// An highlighted block
bool isPointInRect(Point P, Rect rect) {
Point A = rect.tl();
Point B (rect.tl().x + rect.width , rect.tl().y ) ;
Point C(rect.tl().x + rect.width , rect.tl().y + rect.height);
Point D(rect.tl().x , rect.tl().y + rect.height );
int x = P.x;
int y = P.y;
int a = (B.x - A.x)*(y - A.y) - (B.y - A.y)*(x - A.x);
int b = (C.x - B.x)*(y - B.y) - (C.y - B.y)*(x - B.x);
int c = (D.x - C.x)*(y - C.y) - (D.y - C.y)*(x - C.x);
int d = (A.x - D.x)*(y - D.y) - (A.y - D.y)*(x - D.x);
if((a >= 0 && b >= 0 && c >= 0 && d >= 0) || (a <= 0 && b <= 0 && c <= 0 && d <= 0)) {
return true;
}
// AB X AP = (b.x - a.x, b.y - a.y) x (p.x - a.x, p.y - a.y) = (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x);
// BC X BP = (c.x - b.x, c.y - b.y) x (p.x - b.x, p.y - b.y) = (c.x - b.x) * (p.y - b.y) - (c.y - b.y) * (p.x - b.x);
return false;
}
isPointInRect(cv::Point(100,100), Rect(cv::Point(100,100),cv::Point(200,200)));
结果为 1;