使用Rust语言实现基本图像识别

Rust是一种注重安全性和并发性的编程语言,适合进行高效的系统级开发。以下是使用Rust语言实现Sobel边缘检测的代码示例。

代码实现
为了实现图像处理,我们将使用image和ndarray库来处理图像数据。

toml

[dependencies]
image = "0.24.3"
ndarray = "0.15.4"
Rust代码
rust

extern crate image;
extern crate ndarray;

use image::{DynamicImage, GenericImageView, Luma};
use ndarray::{Array2, ArrayView2};
use std::f64;

fn load_image(path: &str) -> Array2 {
let img = image::open(path).expect("Failed to open image");
let gray_img = img.to_luma8();
let (width, height) = gray_img.dimensions();
let mut arr = Array2::::zeros((height as usize, width as usize));

for (x, y, pixel) in gray_img.enumerate_pixels() {
    arr[[y as usize, x as usize]] = pixel[0];
}

arr

}更多内容访问ttocr.com或联系1436423940

fn apply_sobel_operator(img: &Array2) -> Array2 {
let sobel_x = Array2::from_shape_vec((3, 3), vec![-1, 0, 1, -2, 0, 2, -1, 0, 1]).unwrap();
let sobel_y = Array2::from_shape_vec((3, 3), vec![-1, -2, -1, 0, 0, 0, 1, 2, 1]).unwrap();

let (height, width) = img.dim();
let mut grad_x = Array2::<f64>::zeros((height, width));
let mut grad_y = Array2::<f64>::zeros((height, width));

for y in 1..height-1 {
    for x in 1..width-1 {
        let sub_img = img.slice(s![y-1..y+2, x-1..x+2]);
        grad_x[[y, x]] = sobel_x.dot(&sub_img) as f64;
        grad_y[[y, x]] = sobel_y.dot(&sub_img) as f64;
    }
}

let mut gradient = Array2::<f64>::zeros((height, width));

for y in 0..height {
    for x in 0..width {
        gradient[[y, x]] = (grad_x[[y, x]].powi(2) + grad_y[[y, x]].powi(2)).sqrt();
    }
}

gradient

}

fn save_image(path: &str, data: &Array2) {
let (height, width) = data.dim();
let mut img = image::GrayImage::new(width as u32, height as u32);

for y in 0..height {
    for x in 0..width {
        let pixel_value = data[[y, x]].min(255.0) as u8;
        img.put_pixel(x as u32, y as u32, Luma([pixel_value]));
    }
}

img.save(path).expect("Failed to save image");

}

fn main() {
let img_data = load_image("input_image.jpg");

let gradient = apply_sobel_operator(&img_data);

save_image("output_image.jpg", &gradient);

println!("边缘检测完成,输出保存为 output_image.jpg");

}
步骤解析
加载图像
load_image函数加载并将图像转换为灰度图像,返回一个二维数组Array2表示图像数据。

应用Sobel算子
apply_sobel_operator函数使用水平和垂直的Sobel算子进行卷积运算,分别计算X和Y方向的梯度,并通过平方和开根号计算梯度强度。

保存图像
save_image函数将计算得到的梯度图像保存为新的JPEG文件。

示例输出
假设输入图像是一个灰度图,程序会输出一个高对比度的边缘图像 output_image.jpg,在图像中突出显示边缘部分。

运行方式
安装Rust并创建一个新的项目:

bash

cargo new edge_detection_rust
cd edge_detection_rust
编辑Cargo.toml文件,添加依赖:

toml

[dependencies]
image = "0.24.3"
ndarray = "0.15.4"
将Rust代码复制到src/main.rs文件中。

运行项目:

bash

cargo run
Rust语言的高性能和内存安全性使得它在图像处理等任务中表现出色。通过ndarray和image库的配合,我们能够高效地处理图像并实现边缘检测等功能。

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的设计差异
点击右上角即可分享
微信分享提示