> ## 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.

# 快速入门指南

> 使用 QIM SDK 探索目标检测管线

## 目标检测

<img src="https://mintlify.s3.us-west-1.amazonaws.com/qualcomm-prod/zh/SDKs/IMSDK/blogs/images/onj-detect.png" alt="gst-ai-video-detection" />

**给定一个视频帧，识别其中的物体并在其周围绘制边界框**。

<Note>
  请确保已安装 QIMSDK。[QIM SDK 安装指南](installation)
</Note>

## 前提条件

首先在您的设备上运行以下命令：

<Accordion title="设置环境变量">
  ```bash theme={null}
  mkdir -p $HOME/{models,labels,media,media/output}
  export MODEL_NAME=yolo_x_w8a8.tflite
  export LABELS_NAME=yolov8.json
  export SRC_VIDEO_NAME=video.mp4
  ```
</Accordion>

<Accordion title="下载标签、模型和视频文件">
  ```bash theme={null}
  # Download YOLO-X W8A8 model
  curl -L -o $HOME/models/$MODEL_NAME \
    https://huggingface.co/Qualcomm/Yolo-X/resolve/v0.30.5/Yolo-X_w8a8.tflite

  # Download detection labels
  curl -L -o $HOME/labels/$LABELS_NAME \
    https://raw.githubusercontent.com/quic/sample-apps-for-Qualcomm-linux/refs/heads/main/Qualcomm-linux/artifacts/json_labels/yolox.json

  # Download sample video
  curl -L -o $HOME/media/$SRC_VIDEO_NAME \
    https://raw.githubusercontent.com/quic/sample-apps-for-Qualcomm-linux/refs/heads/main/Qualcomm-linux/artifacts/videos/video.mp4
  ```
</Accordion>

***

## 方式 1. 在设备上运行预构建的目标检测应用程序

<Note>
  继续之前，请确保已完成[前提条件](quickstart#prerequisites)
</Note>

<Steps>
  <Step title="配置应用程序">
    覆盖现有的配置文件：

    <Accordion title="写入配置文件">
      ```bash theme={null}
      sudo tee /etc/configs/config_detection.json << EOF
      {
        "file-path": "$HOME/media/$SRC_VIDEO_NAME",
        "ml-framework": "tflite",
        "yolo-model-type": "yolox",
        "model": "$HOME/models/$MODEL_NAME",
        "labels": "$HOME/labels/$LABELS_NAME",
        "threshold": 40,
        "runtime": "dsp",
        "output-type": "waylandsink"
      }
      EOF
      ```
    </Accordion>
  </Step>

  <Step title="运行管线">
    ```bash theme={null}
    gst-ai-object-detection
    ```
  </Step>

  <Step title="查看结果">
    您的显示器现在会显示视频画面，每个检测到的物体周围都绘制了边界框和类别标签。检测结果随每一帧实时更新。<br /> 按 `Ctrl+C` 优雅地停止管线。
  </Step>
</Steps>

这是由许多模块（插件）协同工作形成 `pipeline` 才得以实现的。<br />
让我们再次运行相同的示例，但这次以一种能让您看到所有插件工作情况的方式。

***

## 方式 2. 目标检测管线命令

<Note>
  继续之前，请确保已完成[前提条件](quickstart#prerequisites)
</Note>

<Steps>
  <Step title="运行管线命令">
    ```bash theme={null}
    gst-launch-1.0 -e --gst-debug=2 \
    filesrc location=$HOME/media/$SRC_VIDEO_NAME ! qtdemux ! h264parse ! \
    v4l2h264dec capture-io-mode=4 output-io-mode=4 ! video/x-raw,format=NV12 ! queue ! \
    tee name=t ! qtimetamux name=obj_mux ! qtivoverlay ! waylandsink fullscreen=true sync=false \
    t. ! queue ! qtimlvconverter ! queue ! \
    qtimltflite model=$HOME/models/$MODEL_NAME delegate=external external-delegate-path=libQnnTFLiteDelegate.so external-delegate-options="QNNExternalDelegate,backend_type=htp,log_level=(string)1;" ! queue ! \
    qtimlpostprocess module=yolov8 labels=$HOME/labels/$LABELS_NAME settings="{\"confidence\": 51.0}" ! text/x-raw ! queue ! obj_mux.
    ```
  </Step>

  <Step title="查看结果">
    您的显示器会显示视频画面，每个检测到的物体上都渲染了边界框和类别标签。该管线实时处理帧。<br /> 按 `Ctrl+C` 优雅地停止管线。

    * 如果您想基于此演示进行开发，命令行可能不是最稳健的解决方案
    * 您可以将其粘贴到一个 shell 文件中……
    * 但如果您希望其他代码与之交互，则需要一个 cpp 或 python 文件（管线应用程序）。
  </Step>
</Steps>

***

## 方式 3. 使用 Python 构建您的目标检测管线应用程序

<Note>
  继续之前，请确保已完成[前提条件](quickstart#prerequisites)
</Note>

<Steps>
  <Step title="创建脚本">
    <Accordion title="运行目标检测的 Python 脚本">
      ```bash theme={null}
      cat > obj_det.py << 'PYEOF'
      #!/usr/bin/env python3
      import os, signal, gi
      gi.require_version("Gst", "1.0")
      gi.require_version("GLib", "2.0")
      from gi.repository import Gst, GLib

      SAMPLES = os.environ.get("QIMSDK_SAMPLES", "/etc")
      MODEL   = f"{SAMPLES}/models/{os.environ.get('MODEL_NAME',    'yolo_x_w8a8.tflite')}"
      LABELS  = f"{SAMPLES}/labels/{os.environ.get('LABELS_NAME',   'yolov8.json')}"
      VIDEO   = f"{SAMPLES}/media/{os.environ.get('SRC_VIDEO_NAME', 'video.mp4')}"


      def make(pipeline, factory, **props):
          el = Gst.ElementFactory.make(factory)
          for k, v in props.items():
              el.set_property(k.replace("_", "-"), v)
          pipeline.add(el)
          return el


      def on_demux_pad(demux, pad, next_el):
          if "video" in pad.get_current_caps().to_string():
              pad.link(next_el.get_static_pad("sink"))


      def build_pipeline():
          p = Gst.Pipeline.new()

          src      = make(p, "filesrc",    location=VIDEO)
          demux    = make(p, "qtdemux")
          parse    = make(p, "h264parse")
          decoder  = make(p, "v4l2h264dec", capture_io_mode=4, output_io_mode=4)
          q0       = make(p, "queue")
          tee      = make(p, "tee")

          q1       = make(p, "queue")
          pre_proc = make(p, "qtimlvconverter")
          q2       = make(p, "queue")
          infer    = make(p, "qtimltflite",
                         model=MODEL, delegate="external",
                         external_delegate_path="libQnnTFLiteDelegate.so")
          infer.set_property("external-delegate-options",
                             Gst.Structure.new_from_string(
                                 "QNNExternalDelegate,backend_type=htp,log_level=(string)1"))
          q3       = make(p, "queue")
          post_proc= make(p, "qtimlpostprocess",
                         module="yolov8", labels=LABELS,
                         settings='{"confidence": 51.0}')
          q4       = make(p, "queue")

          mux      = make(p, "qtimetamux")
          q5       = make(p, "queue")
          overlay  = make(p, "qtivoverlay")
          q6       = make(p, "queue")
          sink     = make(p, "waylandsink", fullscreen=True, sync=False)
          q7       = make(p, "queue")

          src.link(demux)
          demux.connect("pad-added", on_demux_pad, parse)
          parse.link(decoder)
          decoder.link_filtered(q0, Gst.Caps.from_string("video/x-raw,format=NV12"))
          q0.link(tee)

          tee.request_pad_simple("src_%u").link(q1.get_static_pad("sink"))
          for a, b in [(q1, pre_proc), (pre_proc, q2), (q2, infer),
                       (infer, q3), (q3, post_proc)]:
              a.link(b)
          post_proc.link_filtered(q4, Gst.Caps.from_string("text/x-raw"))
          q4.link(mux)

          tee.request_pad_simple("src_%u").link(q7.get_static_pad("sink"))
          q7.link(mux)

          for a, b in [(mux, q5), (q5, overlay), (overlay, q6), (q6, sink)]:
              a.link(b)

          return p


      Gst.init(None)
      loop     = GLib.MainLoop()
      pipeline = build_pipeline()

      def on_message(bus, msg):
          if msg.type == Gst.MessageType.ERROR:
              print("Error:", msg.parse_error()[0].message)
          if msg.type in (Gst.MessageType.EOS, Gst.MessageType.ERROR):
              loop.quit()

      pipeline.get_bus().add_watch(GLib.PRIORITY_DEFAULT, lambda b, m: (on_message(b, m), True)[1])
      GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGINT, lambda: loop.quit() or GLib.SOURCE_CONTINUE)

      pipeline.set_state(Gst.State.PLAYING)
      loop.run()
      pipeline.set_state(Gst.State.NULL)
      PYEOF
      ```
    </Accordion>
  </Step>

  <Step title="运行脚本">
    ```bash theme={null}
    python3 obj_det.py
    ```
  </Step>

  <Step title="查看结果">
    您的显示器会显示视频画面，每个检测到的物体上都渲染了边界框和类别标签。该 Python 应用程序实时处理帧。<br /> 按 `Ctrl+C` 优雅地停止管线。
  </Step>
</Steps>

***

## 方式 4. 使用 C++ 构建您的目标检测管线应用程序

[前往构建 AI 管线](qimsdk-overview/sdkoverview)

***

## 工作原理

该管线读取一个 H.264 视频文件，进行硬件解码，将解码后的流分支，在 Qualcomm® AI Engine（HTP 后端）上运行 YOLO-X 推理，对边界框结果进行后处理，使用硬件合成器将标注混合回原始帧，并将输出显示到屏幕上。

**管线示意图**

<img src="https://mintlify.s3.us-west-1.amazonaws.com/qualcomm-prod/zh/SDKs/IMSDK/images/qsg.png" alt="管线示意图" />

***

## 后续步骤

您已经在 Qualcomm® 硬件上以三种不同方式运行了目标检测管线。接下来可以前往：

<CardGroup cols={2}>
  <Card title="AI 示例管线" icon="book-open" href="/zh/SDKs/IMSDK/sample-pipelines/aipipelines">
    可直接运行的 GStreamer 管线，涵盖分类、分割、姿态估计、超分辨率等。
  </Card>

  <Card title="博客" icon="message" href="/zh/SDKs/IMSDK/blogs/blog-index">
    由 QIM SDK 社区构建的真实案例——涵盖目标检测、PPE 合规、安防摄像头等。
  </Card>

  <Card title="支持的模型" icon="people-carry-box" href="/zh/SDKs/IMSDK/supportedmodels">
    在 Qualcomm® 硬件上测试过的量化 TFLite 模型完整目录，并附有每个模型的管线命令。
  </Card>

  <Card title="插件参考" icon="book" href="/zh/SDKs/IMSDK/plugin-reference">
    每个 QIM SDK GStreamer 插件的 API 级文档——属性、caps 和使用示例。
  </Card>
</CardGroup>
