---license: Apache License 2.0inference_framework: ONNX---## 端到端主体检测 ONNX 模型 —— picodet_lcnet_x2_5_640_mainbody### 一、模型简介`picodet_lcnet_x2_5_640_mainbody.onnx` 是基于 PaddleDetection 官方主体检测模型(picodet_lcnet_x2_5_640_mainbody)导出的 ONNX 格式模型。它保持了与原 PaddlePaddle 模型完全一致的端到端输入与输出,可无缝迁移,同时具备跨平台部署的便捷性,尤其适合在低算力终端上高效运行。### 二、核心优势- **端到端推理**:输入图像直接输出检测结果,无需额外后处理脚本,推理流程简洁高效。- **跨平台兼容**:ONNX 格式支持多种硬件和推理后端(CPU/GPU/NPU),便于在边缘设备、服务器等不同环境中部署。- **轻量高效**:基于 LCNet 轻量级骨干网络,在保证检测精度的同时,推理速度优异,资源占用低。### 三、典型应用场景该模型可广泛应用于需要快速定位图像中主要物体的场景,例如:1. **工业视觉质检** —— 精准定位产品主体(如 PCB 板、手机外壳、汽车零部件),排除传送带、夹具等背景干扰,为后续缺陷检测提供稳定 ROI,显著降低误报率。2. **电商商品搜索** —— 自动检测并裁剪商品主体,去除背景及模特干扰,有效提升以图搜图的准确率与召回率。3. **智能驾驶辅助** —— 实时检测路面车辆、行人及交通标志,为路径规划与避障决策提供关键感知数据。4. **视频监控安防** —— 快速识别监控画面中的人员或车辆,用于异常闯入、违规停放等实时告警;同时可作为人脸识别的前置检测模块。5. **内容推荐与广告投放** —— 分析图片主体类别(如美食、风景、人物),辅助判断用户兴趣偏好,从而优化内容推送与广告投放策略。### 四、依赖环境- **ONNX**:1.17.0- **ONNX Runtime**:1.23.2### 五、推理代码示例```pythonimport onnxruntime as ortimport numpy as npimport cv2import timedef preprocess(img, target_size=(640, 640)): """ 预处理函数 """ origin_shape = img.shape[:2] img = cv2.resize(img, target_size) img = img.astype(np.float32) / 255.0 img = img.transpose(2, 0, 1)[np.newaxis, :] # [1,3,640,640] img -= np.array([0.485, 0.456, 0.406], dtype=np.float32).reshape(1, 3, 1, 1) img /= np.array([0.229, 0.224, 0.225], dtype=np.float32).reshape(1, 3, 1, 1) resize_h, resize_w = target_size im_scale_y = resize_h / float(origin_shape[0]) im_scale_x = resize_w / float(origin_shape[1]) scale_factor = np.array([[im_scale_y, im_scale_x]]).astype('float32') inputs = {} inputs['image'] = img inputs['scale_factor'] = scale_factor return inputsdef parse_results(np_boxes, top_k=5, threshold=0.6, label_list=('foreground',)): """ 根据阈值, 过滤结果, 并将结果封装为易读的JSON格式 """ keep_indexes = np_boxes[:, 1].argsort()[::-1][:top_k] results = [] for idx in keep_indexes: item = np_boxes[idx] class_id = int(item[0]) #第一个值:分类ID score = item[1] #第二个值:置信度 bbox = item[2:] #3~6:矩形框4个坐标 if score < threshold: continue label_name = label_list[class_id] results.append({ "class_id": class_id, "score": score, "bbox": bbox, "label_name": label_name }) return resultsdef draw_bbox_results(img, results, save_path): """ 绘制矩形框 """ color = (0, 0, 255) thickness = 2 font = cv2.FONT_HERSHEY_SIMPLEX # 最常用,清晰 font_scale = 0.6 for item in results: bbox = item['bbox'] score = f"{item['score']:.2f}" x1, y1, x2, y2 = map(int, bbox) cv2.rectangle(img, (x1, y1+10), (x2, y2), color, thickness) cv2.putText(img, score, (x1, y1), font, font_scale, color, thickness) cv2.imwrite(save_path, img)def predict(img_file): """ 推理:主体检测 """ # 读取图片与前置处理 img = cv2.imread(img_file) inputs = preprocess(img) # 加载 ONNX 模型 t1 = time.time() config = ort.SessionOptions() config.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL session = ort.InferenceSession("./models/onnx/picodet_lcnet_x2_5_640_mainbody.onnx", sess_options=config) t2 = time.time() print("加载 ONNX 模型,耗时: {} ms ".format(round((t2 - t1) * 1000))) # 推理 input_img_name = session.get_inputs()[0].name input_scale_factor_name = session.get_inputs()[1].name output_name = session.get_outputs()[0].name t1 = time.time() np_boxes = session.run( output_names=[output_name], input_feed={input_img_name: inputs['image'], input_scale_factor_name: inputs['scale_factor']})[0] t2 = time.time() print("推理耗时: {} ms ".format(round((t2 - t1) * 1000))) print("输出结果Shape:", np_boxes.shape, '\n') # 过滤结果 results = parse_results(np_boxes) print("识别结果:\n", results) # 绘制矩形框 draw_bbox_results(img, results, 'result.jpg')"""测试:请输入一张存在的图片"""predict('./images/002.jpeg')```### 六、参考资料- 模型导出过程详解:https://aistudio.baidu.com/projectdetail/10647099- 官方 PaddleDetection 说明:https://gitee.com/paddlepaddle/PaddleDetection/blob/release/2.8.1/configs/picodet/legacy_model/application/mainbody_detection/README.md---如果你在使用过程中遇到任何问题,欢迎在项目评论区留言交流。