ODM_pro/preprocess/grid_divider.py
2024-12-17 22:09:47 +08:00

85 lines
3.2 KiB
Python

import logging
class GridDivider:
"""划分九宫格,并将图片分配到对应网格"""
def __init__(self, overlap=0.1):
self.overlap = overlap
self.logger = logging.getLogger('UAV_Preprocess.GridDivider')
self.logger.info(f"初始化网格划分器,重叠率: {overlap}")
def divide_grids(self, points):
"""计算边界框并划分九宫格"""
self.logger.info("开始划分九宫格")
lats = [p['lat'] for p in points]
lons = [p['lon'] for p in points]
min_lat, max_lat = min(lats), max(lats)
min_lon, max_lon = min(lons), max(lons)
self.logger.info(
f"区域边界: 纬度[{min_lat:.6f}, {max_lat:.6f}], "
f"经度[{min_lon:.6f}, {max_lon:.6f}]"
)
lat_step = (max_lat - min_lat) / 3
lon_step = (max_lon - min_lon) / 3
self.logger.debug(f"网格步长: 纬度{lat_step:.6f}, 经度{lon_step:.6f}")
grids = []
for i in range(3):
for j in range(3):
grid_min_lat = min_lat + i * lat_step - self.overlap * lat_step
grid_max_lat = min_lat + \
(i + 1) * lat_step + self.overlap * lat_step
grid_min_lon = min_lon + j * lon_step - self.overlap * lon_step
grid_max_lon = min_lon + \
(j + 1) * lon_step + self.overlap * lon_step
grids.append((grid_min_lat, grid_max_lat,
grid_min_lon, grid_max_lon))
self.logger.debug(
f"网格[{i},{j}]: 纬度[{grid_min_lat:.6f}, {grid_max_lat:.6f}], "
f"经度[{grid_min_lon:.6f}, {grid_max_lon:.6f}]"
)
self.logger.info(f"成功划分为 {len(grids)} 个网格")
return grids
def assign_to_grids(self, points, grids):
"""将点分配到对应网格"""
self.logger.info(f"开始将 {len(points)} 个点分配到网格中")
grid_points = {i: [] for i in range(len(grids))}
points_assigned = 0
multiple_grid_points = 0
for point in points:
point_assigned = False
for i, (min_lat, max_lat, min_lon, max_lon) in enumerate(grids):
if min_lat <= point['lat'] <= max_lat and min_lon <= point['lon'] <= max_lon:
grid_points[i].append(point)
if point_assigned:
multiple_grid_points += 1
else:
points_assigned += 1
point_assigned = True
self.logger.debug(
f"{point['file']} (纬度: {point['lat']:.6f}, 经度: {point['lon']:.6f}) "
f"被分配到网格"
)
# 记录每个网格的点数
for grid_idx, points in grid_points.items():
self.logger.info(f"网格 {grid_idx} 包含 {len(points)} 个点")
self.logger.info(
f"点分配完成: 总点数 {len(points)}, "
f"成功分配 {points_assigned} 个点, "
f"{multiple_grid_points} 个点被分配到多个网格"
)
return grid_points