1

我正在尝试重新进行 Photoshop 调整图层样式过程,其中图像处理功能由堆栈中的图层表示,其中顶部/第一个过程的结果被馈送到下一个过程。这可以表示为处理函数的数组,其中每个函数的输出被馈送到下一个函数。

[Change Brightness(img)->Change Saturation(img)->Change Levels(img)]

我怎样才能从 Rust 中的非静态函数数组中实现这种“传递”值?

fn op_a(mut a: Vec<u8>, p1: i32) -> Vec<u8> {
    //process image
    println!("Operation A on image with size: {}, and parameter1 val: {}", a.len(), p1);
    a[0] = 10;
    a
}

fn op_b(mut a: Vec<u8>, p1: i32, p2: i32) -> Vec<u8> {
    //process image
    println!("Operation B on image with size: {}, parameter 1 val: {}, parameter 2 val: {}", a.len(), p1, p2);
    a[0] += 2;
    a
}

fn op_c(mut a: Vec<u8>, p1: i32, p2: i32, p3: i32) -> Vec<u8> {
    //process image
    println!("Operation C on image with size: {}, parameter 1 val: {}, parameter 2 val: {}, parameter 3 val: {}", a.len(), p1, p2, p3);
    a[0] *= 2;
    a
}

fn pipe_function_array(initial_image: ImageBuffer, Vec<functions>)->ImageBuffer{
        //executes an array of functions passing each to the next function in the array, with an initual input value of initial_image
    
}

fn main() {
    let my_starting_value =  *some Vec<u8>*;
    let my_funcs = *an array of op_a, op_b, and op_c*;
    let final_image = pipe_function_array(vec![0], my_funcs);
}

ps调整图层

4

1 回答 1

1

一旦你修复了明显的语法错误,你的代码基本上就可以工作了。

fn op_a(mut a: Vec<u8>) -> Vec<u8> {
    //process image
    println!("Operation A on image with size: {}", a.len());
    a[0] = 10;
    a
}

fn op_b(mut a: Vec<u8>) -> Vec<u8> {
    //process image
    println!("Operation B on image with size: {}", a.len());
    a[0] += 2;
    a
}

fn op_c(mut a: Vec<u8>) -> Vec<u8> {
    //process image
    println!("Operation C on image with size: {}", a.len());
    a[0] *= 2;
    a
}

fn pipe_function_array(initial_image: Vec<u8>, a: Vec<fn(Vec<u8>) -> Vec<u8>>) -> Vec<u8> {
    //Using fold here, but you can easily just use a for loop if you prefer.
    a.iter()
        .fold(initial_image, |image, operation| (operation)(image))
}

fn main() {
    // You have to define the type of the Vec here, 
    // otherwise the compiler will throw some ambiguous errors.
    let my_funcs: Vec<fn(Vec<u8>) -> Vec<u8>> = vec![op_a, op_b, op_c];

    let final_image = pipe_function_array(vec![0], my_funcs);
    dbg!(final_image);
}

操场


但是,我建议不要直接传递函数指针,而是采用不同的方法来使用枚举数组。

enum Operations {
    Saturation {
        config: SaturationConfig,
    },
    Contrast {
        config: ContrastConfig,
    }
}

fn saturation(mut a: Vec<u8>, config: SaturationConfig) -> Vec<u8> {
    //process image
    a
}
fn contrast(mut a: Vec<u8>, config: ContrastConfig) -> Vec<u8> {
    //process image
    a
}

fn pipe_function_array(mut initial_image: Vec<u8>, a: Vec<Operations>) -> Vec<u8> {
    a.iter()
        .fold(initial_image, |image, operation| match operation {
            Operations::Saturation { config } => saturation(image, config),
            Operations::Contrast { config } => contrast(image, config),
        })
}
于 2020-12-28T04:27:29.253 回答