Python实现bounding box等面积分割为多个等尺寸子框
实现方案
你已经用numpy生成了等间隔的经纬度序列,不用写复杂的嵌套逻辑,用numpy的网格能力就能快速生成所有小矩形顶点,代码简单运行也快。
先明确下坐标对应关系:你生成的cols是经度(东西向)序列,rows是纬度(南北向)序列,传入num=15意味着每条边切14段,最终会得到14*14=196个面积完全相等的小矩形。
代码实现
易读版(适合初学者)
这个版本逻辑直白,你能很清楚看到每个顶点是怎么取的,日常使用性能完全够用:
import numpy as np # 你已有的边界框定义 bottom_left = [10.7510994291,106.5517721598] bottom_right = [10.7510994291,106.7500970722] top_right = [10.9005609767,106.7500970722] top_left = [10.9005609767,106.5517721598] # 你已有的等间隔坐标生成代码 cols = np.linspace(bottom_left[1], bottom_right[1], num=15) # 经度序列 rows = np.linspace(bottom_left[0], top_left[0], num=15) # 纬度序列 # 生成网格点矩阵 lon_grid, lat_grid = np.meshgrid(cols, rows) all_boxes = [] # 遍历所有相邻点组合,生成小矩形 for lat_idx in range(len(rows) - 1): for lon_idx in range(len(cols) - 1): # 四个顶点按[经度, 纬度]格式存储,和你给出的示例格式一致 single_box = [ [lon_grid[lat_idx, lon_idx], lat_grid[lat_idx, lon_idx]], [lon_grid[lat_idx, lon_idx], lat_grid[lat_idx+1, lon_idx]], [lon_grid[lat_idx, lon_idx+1], lat_grid[lat_idx, lon_idx]], [lon_grid[lat_idx, lon_idx+1], lat_grid[lat_idx+1, lon_idx+1]] ] all_boxes.append(single_box)
运行后all_boxes里存的就是所有小矩形的顶点,打印第一个元素就能得到你示例里的第一个小框,坐标完全匹配,只是默认保留了完整精度,需要固定小数位的话加个round()处理就行。
纯向量化无循环版(效率更高)
如果之后要做更细粒度的切分(比如上百个分段),可以用numpy的滑动窗口接口实现完全无循环的计算,速度更快:
from numpy.lib.stride_tricks import sliding_window_view # 把网格点拼成[经度,纬度]格式的坐标矩阵 point_matrix = np.stack([lon_grid, lat_grid], axis=-1) # 取2*2的滑动窗口,每个窗口就是一个小矩形的四个顶点 all_boxes = sliding_window_view(point_matrix, window_shape=(2,2), axis=(0,1)).reshape(-1,4,2).tolist()
补充说明
- 你给出的第二个示例框跨了两个经度分段,应该是手误,正常等面积切分的所有小矩形,都是由相邻两个经度点、相邻两个纬度点围成的,和第一个示例格式一致
- 因为你用
np.linspace做的是等间隔切分,最终生成的所有小矩形经纬度跨度完全一致,面积相等
内容的提问来源于stack exchange,提问作者Nguyen Hoang Vu
相关产品推荐
相关产品推荐

