本期带来的是Rust下的图像处理库,image-rs。
Github: image-rs repoDocs rs: image-rs doc根据Github仓库页面的介绍,image-rs提供了基础的图像处理功能和图像格式转换功能。
所有的图像处理函数都通过GenericImage和ImageBuffer完成。
image-rs支持的图像格式如下:
从上图我们可以看出image-rs基本支持了应用中常见的图像容器格式类型。
关于ImageDecoder和ImageDecoderExt 所有的图像格式decoders都包含了ImageDecoder实现,其中主要过程是从图像文件中获取图像的metadata并解码图像。
其中一些decoders的比较重要的参数包括:
dimensions:返回包含图像的宽度和高度的元组数据color_type:返回由decoder返回的图像的色彩类型read_image:把图像解码成bytes关于像素,image提供了如下几种像素类型:
Rgb: 包含Rgb像素Rgba: 包含Rgba像素(a为alpha,透明通道)Luma: 灰度像素LumaA: 包含alpha通道的灰度像素图像处理函数包含:
blur:使用高斯模糊来处理图像brighten:图像高亮处理huerotate: 旋转色彩空间contrast: 调整图像的对比度crop: 剪裁图像filter3x3:使用3x3的矩阵来处理图像,可用于图像降噪,升噪grayscale: 灰度化图像flip_horizontal: 水平翻转图像flip_vertical: 垂直翻转图像invert: 对图像的每个像素求反resize: 改变图像尺寸rotate180: 图像顺时针旋转180度rotate270: 图像顺时针旋转270度rotate90: 图像顺时针unsharpen: 降低图像锐度下面我们通过image-rs Github仓库的Generating Fractals例子来试用image-rs库
开发环境:
Windows 10cargo --version: 1.39.0rustc --version: 1.39.0根据示例代码,只需要在dependencies中添加引用
[dependencies] image = "0.23.4" num-complex = "0.2.4"修改源文件main.rs如下
extern crate image; extern crate num_complex; fn main() { let imgx = 800; let imgy = 800; let scalex = 3.0 / imgx as f32; let scaley = 3.0 / imgy as f32; // Create a new ImgBuf with width: imgx and height: imgy let mut imgbuf = image::ImageBuffer::new(imgx, imgy); // Iterate over the coordinates and pixels of the image for (x, y, pixel) in imgbuf.enumerate_pixels_mut() { let r = (0.3 * x as f32) as u8; let b = (0.3 * y as f32) as u8; *pixel = image::Rgb([r, 0, b]); } // A redundant loop to demonstrate reading image data for x in 0..imgx { for y in 0..imgy { let cx = y as f32 * scalex - 1.5; let cy = x as f32 * scaley - 1.5; let c = num_complex::Complex::new(-0.4, 0.6); let mut z = num_complex::Complex::new(cx, cy); let mut i = 0; while i < 255 && z.norm() <= 2.0 { z = z * z + c; i += 1; } let pixel = imgbuf.get_pixel_mut(x, y); let image::Rgb(data) = *pixel; *pixel = image::Rgb([data[0], i as u8, data[2]]); } } // Save the image as “fractal.png”, the format is deduced from the path imgbuf.save("fractal.png").unwrap(); }使用命令cargo build编译,使用命令cargo run运行,即可在工程根目录下生成名为fractal.png的图片
---来自腾讯云社区的---MikeLoveRust
微信扫一扫打赏
支付宝扫一扫打赏