简体   繁体   中英

Convert Mat to Vec<u8> (Rust OpenCV)

I'm really new to Rust and fairly new to OpenCV (yea).

I have a simple OpenCV example working in a seperate POC. But then integrating it into a workflow pipeline I need to return a buffer in type Vec<u8> .

Img is a Mat object which has this to_vec_2d method. But I'm unsure how to cast it to u8?

I'm thinking I might have to iterate through the Mat type. Is it possible to map it u8?

fn edge_detect(width: u32, height: u32, bytes: Vec<u8>, _metadata: Metadata) -> (u32, u32, Vec<u8>) {
    let img = imdecode(&Vector::from_iter(bytes), imgcodecs::IMREAD_ANYCOLOR).expect("Failed to decode");
    let mut result = img.clone();
    canny(&img, &mut result, 100.0, 200.0, 3, false).expect("Failed to find edges");
    let vec_result : Vec<u8> = result.to_vec_2d().expect("Cannot convert to vector");
    (width, height, vec_result)
}

在此处输入图像描述

You can use flat_map on an iterator to get them:

fn main() {
    let vec_2d = vec![vec![0, 1], vec![2, 3]];
    let v: Vec<u8> = vec_2d.iter().flat_map(|v| v.iter()).cloned().collect();
    println!("{:?}", v);
}

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM