Python如何判断XY坐标是否落在指定矩形感兴趣区域(ROI)范围内
实现思路
矩形ROI的点校验本质是做边界数值对比,只要点的X坐标落在ROI的X轴区间内、Y坐标落在ROI的Y轴区间内,即可判定该点在ROI中。你有两种参数输入方式可选:
- 方式1:已提前计算好ROI的
x_min(ROI最左侧X值)、x_max(ROI最右侧X值)、y_min(ROI最底部Y值)、y_max(ROI最顶部Y值),直接做区间判断即可 - 方式2:仅持有ROI中心坐标
(roi_cx, roi_cy)和ROI的宽、高数值,可先通过计算得到上述四个边界值再做判断
完整代码示例
def is_point_in_roi(point_x: float, point_y: float, roi_x_min: float, roi_x_max: float, roi_y_min: float, roi_y_max: float) -> bool: """判断单个点是否落在矩形ROI内""" return roi_x_min <= point_x <= roi_x_max and roi_y_min <= point_y <= roi_y_max def batch_check_points(points: list[tuple[float, float]], roi_params: dict) -> list[tuple[float, float, bool]]: """ 批量校验多个点是否在ROI内 :param points: 待校验的点列表,每个元素为(x, y)格式的坐标元组 :param roi_params: ROI参数,支持两种格式: 1. 直接传入边界:{'x_min': xx, 'x_max': xx, 'y_min': xx, 'y_max': xx} 2. 传入中心+宽高:{'cx': xx, 'cy': xx, 'width': xx, 'height': xx} """ # 处理ROI参数 if 'cx' in roi_params: # 从中心和宽高计算边界 half_w = roi_params['width'] / 2 half_h = roi_params['height'] / 2 x_min = roi_params['cx'] - half_w x_max = roi_params['cx'] + half_w y_min = roi_params['cy'] - half_h y_max = roi_params['cy'] + half_h else: x_min = roi_params['x_min'] x_max = roi_params['x_max'] y_min = roi_params['y_min'] y_max = roi_params['y_max'] # 批量校验 result = [] for x, y in points: in_roi = is_point_in_roi(x, y, x_min, x_max, y_min, y_max) result.append((x, y, in_roi)) return result # 调用示例 if __name__ == '__main__': # 示例待校验点 test_points = [(100, 200), (-50, 30), (200, -150), (-300, 200)] # 示例ROI参数(中心在(0,50),宽400,高300) roi_cfg = {'cx': 0, 'cy': 50, 'width': 400, 'height': 300} # 也可以用边界方式传参:roi_cfg = {'x_min': -200, 'x_max': 200, 'y_min': -100, 'y_max': 200} check_result = batch_check_points(test_points, roi_cfg) for x, y, in_roi in check_result: print(f"点({x}, {y})是否在ROI内:{in_roi}")
注意事项
- 如果你持有的是ROI左上角、右下角的笛卡尔坐标,注意正常笛卡尔坐标系中左上角的Y值大于右下角的Y值,所以计算
y_min时取右下角Y值,y_max取左上角Y值即可,X值直接取左右边界即可 - 如果你的Y轴是屏幕像素的向下为正的坐标系,只需要调整
y_min和y_max的计算逻辑即可,区间判断规则不变 - 如果仅需要判断ROI内是否至少存在一个符合要求的点,不需要返回全部校验结果,可在校验到第一个符合条件的点时直接终止循环返回
True,提高运行效率
内容的提问来源于stack exchange,提问作者Phoenix
相关产品推荐
相关产品推荐

