rust(49)-图像(2)

GenericImage Trait
trait,提供操作图像的函数,参数化图像的像素类型。

# use image::{Pixel, Pixels};
pub trait GenericImage {
    /// The pixel type.
    type Pixel: Pixel;

    /// The width and height of this image.
    fn dimensions(&self) -> (u32, u32);

    /// The bounding rectangle of this image.
    fn bounds(&self) -> (u32, u32, u32, u32);

    /// Return the pixel located at (x, y)
    fn get_pixel(&self, x: u32, y: u32) -> Self::Pixel;

    /// Put a pixel at location (x, y)
    fn put_pixel(&mut self, x: u32, y: u32, pixel: Self::Pixel);

    /// Return an Iterator over the pixels of this image.
    /// The iterator yields the coordinates of each pixel
    /// along with their value
    fn pixels(&self) -> Pixels<Self>;
}

图像的表征
图像提供了两种主要的表示图像数据的方法:

ImageBuffer

由像素类型参数化的图像,由像素的宽度、高度和向量表示。它提供了对其像素的直接访问,并实现了GenericImage Trait。

extern crate image;

use image::{GenericImage, GenericImageView, ImageBuffer, RgbImage};

// Construct a new RGB ImageBuffer with the specified width and height.
let img: RgbImage = ImageBuffer::new(512, 512);

// Construct a new by repeated calls to the supplied closure.
let mut img = ImageBuffer::from_fn(512, 512, |x, y| {
    if x % 2 == 0 {
        image::Luma([0u8])
    } else {
        image::Luma([255u8])
    }
});

// Obtain the image's width and height.
let (width, height) = img.dimensions();

// Access the pixel at coordinate (100, 100).
let pixel = img[(100, 100)];

// Or use the `get_pixel` method from the `GenericImage` trait.
let pixel = *img.get_pixel(100, 100);

// Put a pixel at coordinate (100, 100).
img.put_pixel(100, 100, pixel);

// Iterate over all pixels in the image.
for pixel in img.pixels() {
    // Do something with pixel.
}
发布了473 篇原创文章 · 获赞 14 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/AI_LX/article/details/105011909
49