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::
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
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庫的配合,我們能夠高效地處理影像並實現邊緣檢測等功能。