物体检测(YOLO)示例:使用 Rust 调用 Python 进行物体检测

在本示例中,我们将展示如何使用 Rust 调用 Python 脚本来完成 YOLO 物体检测任务。我们将通过 Rust 的 std::process::Command 调用 Python 脚本,并传递输入图像以进行检测。

  1. 环境准备
    首先,您需要安装以下工具:
    更多内容访问ttocr.com或联系1436423940
    Rust 语言:从 Rust 官网 安装 Rust。
    Python 和必要的库:安装 Python,并确保安装了 torch 和 opencv-python 等库:
    bash

pip install torch opencv-python
2. Python 物体检测脚本
首先,我们编写一个 Python 脚本来执行 YOLO 物体检测任务。这个 Python 脚本将使用预训练的 YOLOv5 模型来检测图像中的物体。

Python 脚本:detect.py

python

import torch
import cv2
import sys

def detect_objects(image_path):
# 加载预训练的YOLOv5模型
model = torch.hub.load('ultralytics/yolov5', 'yolov5s') # 使用YOLOv5小型模型

# 读取图片
img = cv2.imread(image_path)

# 使用YOLO进行物体检测
results = model(img)

# 获取检测结果并显示
results.show()  # 显示图片
results.save()  # 保存结果到文件

# 返回检测的标签和得分
labels = results.names
boxes = results.xywh[0].tolist()  # 获取边界框
return labels, boxes

if name == "main":
image_path = sys.argv[1] # 从命令行参数获取图片路径
labels, boxes = detect_objects(image_path)
print("Detected labels:", labels)
print("Bounding boxes:", boxes)
该 Python 脚本会:

加载 YOLO 模型并读取输入图像。
使用 YOLO 进行物体检测。
显示检测结果并保存为图像。
打印检测的标签和边界框坐标。
3. Rust 调用 Python 脚本
在 Rust 中,我们将使用标准库中的 std::process::Command 来调用 Python 脚本。我们将图像路径作为参数传递给 Python 脚本,并处理其输出。

Rust 脚本:main.rs

rust

use std::process::{Command, Stdio};
use std::io::{self, Write};

fn detect_objects(image_path: &str) -> io::Result<()> {
// 使用 Command 运行 Python 脚本并传递图像路径作为参数
let output = Command::new("python")
.arg("detect.py")
.arg(image_path)
.output()?;

// 检查脚本是否执行成功
if !output.status.success() {
    eprintln!("Error running Python script");
    eprintln!("stderr: {}", String::from_utf8_lossy(&output.stderr));
    return Err(io::Error::new(io::ErrorKind::Other, "Python script failed"));
}

// 打印 Python 脚本的标准输出
println!("Python script output: {}", String::from_utf8_lossy(&output.stdout));

Ok(())

}

fn main() -> io::Result<()> {
// 设置图像路径
let image_path = "test_image.jpg";

// 调用 Python 脚本执行物体检测
detect_objects(image_path)?;

println!("Object detection completed successfully!");

Ok(())

}
在这个 Rust 脚本中,我们:

使用 std::process::Command 来执行 Python 脚本 detect.py,并将图像路径作为参数传递给脚本。
捕获并处理 Python 脚本的标准输出和标准错误输出。
打印 Python 脚本的执行结果。
4. 配置 Rust 和 Python 环境
确保您的 Rust 环境已安装,并且 Python 环境已经配置好,并且能够执行 detect.py。

安装 Rust:从 Rust 官网 安装 Rust。
安装 Python 和必要的库:
bash

pip install torch opencv-python
5. 编译和运行
在终端中编译并运行 Rust 程序:

bash

cargo run
该命令会调用 Python 脚本来进行物体检测,并打印检测结果。

posted @   ttocr、com  阅读(87)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示