Flask应用中调整YOLO摄像头画面后Bounding Box异常问题求助
YOLO摄像头画面尺寸适配与Bounding Box修正方案
问题根源
你的代码里存在冗余且错误的坐标缩放步骤:
- YOLO返回的
box.xyxy[0]本身就是原始图像的像素坐标,不需要先按目标尺寸反向缩放 - 两次无意义的缩放操作导致Bounding Box坐标严重偏移,最终显示异常
修正后的代码
def RunYOLOWebcam(path_x): # 启动摄像头 cap = cv2.VideoCapture(path_x) desired_width = 540 desired_height = 300 # 加载YOLO模型 model = YOLO("best.pt") # 初始化类别名称(A-Z) classNames = [chr(65 + i) for i in range(26)] while True: success, img = cap.read() if not success: break # 对原始图像执行YOLO检测 results = model(img, stream=True) # 计算图像缩放比例 scale_x = desired_width / img.shape[1] scale_y = desired_height / img.shape[0] # 调整图像到目标尺寸 img_resized = cv2.resize(img, (desired_width, desired_height)) # 遍历检测结果,转换Bounding Box坐标并绘制 for r in results: boxes = r.boxes for box in boxes: # 获取原始图像上的Bounding Box坐标 x1, y1, x2, y2 = box.xyxy[0] x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2) # 将坐标缩放至目标图像尺寸 x1_resized = int(x1 * scale_x) y1_resized = int(y1 * scale_y) x2_resized = int(x2 * scale_x) y2_resized = int(y2 * scale_y) # 在缩放后的图像上绘制Bounding Box cv2.rectangle(img_resized, (x1_resized, y1_resized), (x2_resized, y2_resized), (255, 0, 255), 3) yield img_resized cv2.destroyAllWindows()
关键修改说明
- 移除了冗余的中间变量,简化检测-转换-绘制的流程
- 提前计算缩放比例,直接将原始图像的Bounding Box坐标映射到目标尺寸图像上
- 去掉无意义的坐标反向缩放步骤,彻底避免坐标偏移问题
- 简化类别名称初始化代码,保持功能不变
内容的提问来源于stack exchange,提问作者S_04
相关产品推荐
相关产品推荐

