> ## Documentation Index
> Fetch the complete documentation index at: https://dragonwingdocs.qualcomm.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 使用 sample_object_detection 检测物体

`sample_object_detection` 示例应用使用 ROS 2 节点检测并分类图像中的物体。它使用 Qualcomm® AI Engine Direct SDK (QNN) 进行模型推理。

该示例使用 Ultralytics YOLOv8 模型来预测图像中物体的边界框和类别。

<Note>
  **注意**

  有关更多信息，请参见 GitHub 上的 [sample\_object\_detection](https://github.com/qualcomm-qrb-ros/qrb_ros_samples/tree/main/ai_vision/sample_object_detection)。
</Note>

<video
  autoPlay
  muted
  loop
  playsInline
  width={320}
  height={320}
  src="https://mintlify.s3.us-west-1.amazonaws.com/qualcomm-prod/zh/SDKs/QIR-SDK-2.0/media/80-65220-2-qirp-sdk-qsg/sample_object_detection_result.mp4"
  style={{
width: "50%",
display: "block",
margin: "0 auto" }}
/>

<p style={{ textAlign: 'center', fontWeight: 'bold' }}>
  图：`sample_object_detection` 的示例效果
</p>

## `sample_object_detection` 的流水线流程

<img src="https://mintlify.s3.us-west-1.amazonaws.com/qualcomm-prod/zh/SDKs/QIR-SDK-2.0/media/80-65220-2-qirp-sdk-qsg/object_detection_pipeline-regenerate.svg" style={{width: "100%"}} />

<p style={{ textAlign: 'center', fontWeight: 'bold' }}>
  图：`sample_object_detection` 的流水线流程
</p>

## `sample_object_detection` 中使用的 ROS 节点

| **ROS 节点**                                                                          | **说明**                                     |
| :---------------------------------------------------------------------------------- | :----------------------------------------- |
| [qrb\_ros\_camera](https://github.com/qualcomm-qrb-ros/qrb_ros_camera)              | Qualcomm ROS 2 包，使用参数捕获图像并将其发布到 ROS topic。 |
| [yolo\_preprocess](https://github.com/qualcomm-qrb-ros/qrb_ros_tensor_process)      | 订阅图像数据，重塑并调整其大小，然后重新发布到下游 topic。           |
| [qrb\_ros\_nn\_inference](https://github.com/qualcomm-qrb-ros/qrb_ros_nn_inference) | 加载训练好的 AI 模型，接收预处理后的图像，执行推理并发布结果。          |
| [yolo\_postprocess](https://github.com/qualcomm-qrb-ros/qrb_ros_tensor_process)     | 将推理输出与 YOLO 标签文件进行匹配。                      |
| [yolo\_overlay](https://github.com/qualcomm-qrb-ros/qrb_ros_tensor_process)         | 订阅 YOLO 后处理和图像数据，将物体检测结果显示为 ROS topic。     |

## `sample_object_detection` 中使用的 ROS topic

| **ROS topic**                 | **类型**                                    | **发布者**                           |
| :---------------------------- | :---------------------------------------- | :-------------------------------- |
| `/cam0_stream1`               | `sensor_msgs.msg.Image`                   | `camera_node`                     |
| `/qrb_inference_input_tensor` | `qrb_ros_tensor_list_msgs.msg.TensorList` | `yolo_preprocess_node`            |
| `/resized_image`              | `sensor_msgs.msg.Image`                   | `yolo_preprocess_node`            |
| `/yolo_detect_tensor_output`  | `qrb_ros_tensor_list_msgs.msg.TensorList` | `nn_inference_node`               |
| `/yolo_detect_result`         | `vision_msgs.msg.Detection2DArray`        | `yolo_detection_postprocess_node` |
| `/yolo_detect_overlay`        | `sensor_msgs.msg.Image`                   | `yolo_detection_overlay_node`     |

<Note>
  **注意**

  `yolo_detection_overlay_node` 使用严格时间戳（exact-time）策略同步 `/yolo_detect_result` 和 `/resized_image` 两个输入。两者都必须处于发布状态，才能产生 `/yolo_detect_overlay`。
</Note>

## 前提条件

* 你已完成 [设置运行示例应用的环境](./set-up-env-for-sample-app) 中的设置。
* 你已按以下步骤在主机计算机上使用 QAI-Hub 生成了 YOLOv8 模型。

## 生成 YOLOv8 模型

1. 在主机计算机上设置 QAI-Hub。
   1. 登录 [QAI-Hub](https://app.aihub.qualcomm.com/docs/hub/getting_started.html) 并获取你的 API token。
   2. 安装 QAI-Hub。
      ```python theme={null}
      ## It is recommended to use python venv to avoid impacting the host environment.
      python3 -m venv venv_qaihub
      source venv_qaihub/bin/activate
      ## Install QAI-Hub related python packages.
      pip3 install qai-hub==0.41.0
      ## Configure QAI-Hub token, replacing xxx with your own token got from QAI-Hub page.
      qai-hub configure --api_token xxx
      pip3 install "qai-hub-models[yolov8-det]==0.42.0"
      ```
2. 在主机计算机上导出模型。
   ```python theme={null}
   # For IQ-9075, after executing the following commands, the model file and coco8.yaml are generated in the host computer.
   python -m qai_hub_models.models.yolov8_det.export --target-runtime "qnn_context_binary" --chipset "qualcomm-qcs9075-proxy" --skip-profiling --skip-inferencing --compile-options='--qairt_version=2.41'
   ```
   ```bash title="SSH Session" theme={null}
   # Push model files to the device's default path according to the preceding export log.
   # On the device, create the path if it doesn't exist.
   mkdir /opt/model
   ```
   ```bash theme={null}
   # On the host computer, scp all model files to the device.
   scp <Host_Export_model_Path>/yolov8_det_float/yolov8_det.bin root@<device_ip>:/opt/model
   scp <Host_Export_model_Path>/coco8.yaml root@<device_ip>:/opt/
   ```

有关更多信息，请参见 GitHub 上的 [qrb\_ros\_tensor\_process](https://github.com/qualcomm-qrb-ros/qrb_ros_tensor_process/tree/main/cv_tensor_process/yolo_v8_process)。

## 开箱即用运行 `sample_object_detection`

<Accordion title="试一试">
  <Steps>
    <Step title="在开发套件上运行示例">
      ```bash title="SSH Session" theme={null}
      # Set up the runtime environment
      source /usr/share/qirp-setup.sh -m
      # Set the ROS_DOMAIN_ID
      export ROS_DOMAIN_ID=123
      # Launch the sample object detection
      ros2 launch sample_object_detection launch_with_qrb_ros_camera.py model:=/opt/model/yolov8_det.bin
      ```
    </Step>

    <Step title="在主机计算机上检查结果">
      在主机计算机的终端中，用 `rqt` 检查名称为 `/yolo_detect_overlay` 的 ROS topic。
    </Step>
  </Steps>
</Accordion>

## 构建并运行 `sample_object_detection`

以下步骤以 Dragonwing IQ-9075 Evaluation Kit 为例构建 `sample_object_detection` 包。

<Accordion title="试一试">
  <Steps>
    <Step title="在主机计算机上构建并打包">
      1. 构建示例应用项目。
         ```bash theme={null}
         cd <decompressed_workspace>/images/iq-9075-evk/qirpsdk_artifacts/iq-9075-evk/
         tar -zxvf qirp-sdk_<qirp_version>.tar.gz
         cd qirp-sdk
         source setup.sh
         # build sample
         cd <qirp_decompressed_path>/qirp-samples/ai_vision/sample_object_detection
         colcon build
         ```
      2. 打包并将示例应用推送到设备。
         ```bash theme={null}
         # package and push build result of sample
         cd <qirp_decompressed_path>/qirp-samples/ai_vision/sample_object_detection/install/sample_object_detection
         tar -czvf sample_object_detection.tar.gz lib share
         scp sample_object_detection.tar.gz root@[ip-addr]:/opt/
         ```
    </Step>

    <Step title="在开发套件上安装并运行">
      1. 安装示例应用。
         ```bash title="SSH Session" theme={null}
         # Install sample package
         tar --no-overwrite-dir --no-same-owner -zxf /opt/sample_object_detection.tar.gz -C /usr/ros/jazzy/
         ```
      2. 按照 [开箱即用运行 sample\_object\_detection](#run-out-of-the-box-sample_object_detection) 中的步骤运行示例应用。
    </Step>
  </Steps>
</Accordion>
