基于Yolov7棕榈树检测:Bounding Box中心点坐标获取及GPS定位求助
获取YOLOv7检测框中心点坐标并转换为GPS位置的解决方案
一、计算检测框中心点坐标
YOLOv7输出的检测框默认以(x1, y1, x2, y2)格式返回,其中(x1,y1)是框的左上角坐标,(x2,y2)是右下角坐标。要得到中心点,直接用以下公式计算:
# det_box为单个检测框的坐标数组,格式为[x1, y1, x2, y2] x_center = (det_box[0] + det_box[2]) / 2 y_center = (det_box[1] + det_box[3]) / 2
二、在YOLOv7推理流程中集成计算逻辑
如果是基于官方detect.py做开发,找到检测结果遍历的代码段(通常是for *xyxy, conf, cls in reversed(det)),直接添加中心点计算:
for *xyxy, conf, cls in reversed(det): x1, y1, x2, y2 = xyxy # 计算中心点坐标 x_center = (x1 + x2) / 2 y_center = (y1 + y2) / 2 # 此处可直接将中心点坐标存入列表,或用于后续GPS转换
三、像素坐标转GPS位置
要把像素中心点转换成实际GPS坐标,需结合图像的地理配准信息,两种常见实现方式:
- 已知图像四角GPS坐标:通过透视变换建立像素与GPS的映射,用OpenCV即可实现:
import cv2 import numpy as np # 图像四角的像素坐标(左上、右上、右下、左下) pixel_corners = np.float32([[0,0], [img_w,0], [img_w,img_h], [0,img_h]]) # 对应四角的GPS坐标(格式:[纬度, 经度],需转为浮点型) gps_corners = np.float32([[lat1, lon1], [lat2, lon2], [lat3, lon3], [lat4, lon4]]) # 生成透视变换矩阵 transform_matrix = cv2.getPerspectiveTransform(pixel_corners, gps_corners) # 将中心点像素坐标转为GPS坐标 center_pixel = np.float32([[x_center, y_center]]) gps_coords = cv2.perspectiveTransform(center_pixel, transform_matrix)[0] # gps_coords即为中心点对应的[纬度, 经度]
- 无人机图像带EXIF元数据:如果是无人机拍摄的图像,可结合EXIF中的GPS信息、相机内参,通过摄影测量公式计算地面GPS位置,具体可参考无人机摄影测量的相关转换逻辑。
四、验证中心点效果
计算完成后,可在图像上绘制中心点验证准确性:
# 用红色实心圆标记中心点 cv2.circle(img, (int(x_center), int(y_center)), 5, (0,0,255), -1) # 保存验证图像 cv2.imwrite('palms_with_centers.jpg', img)
内容的提问来源于stack exchange,提问作者anselme kadio
相关产品推荐
相关产品推荐

