raimohanska
raimohanska

Reputation: 3405

How to use Rust OpenCV imdecode

I'd like decode a PNG image into an OpenCV Mat object using imdecode. I'm working on a function like

fn handle_frame(buf: &[u8]) -> Result<(), opencv::Error> {
    original_image: Mat = imgcodecs::imdecode(buf, imgcodecs::IMREAD_COLOR)?;    

    let width = original_image.cols()?;
    let height = original_image.rows()?;

    println!("Success! Dimensions are {}x{}", width, height);

    Ok(())
}

But I cannot pass by byte buffer to imdecode because I'd first need to convert it to something that has the ToInputArray trait. How to do this?

Upvotes: 3

Views: 1478

Answers (2)

sbeskur
sbeskur

Reputation: 2290

Here is a mostly complete example:

let filename = "somepicture.png";
let mut reader: Box<dyn BufRead> = Box::new(BufReader::new(File::open(filename)?));
let mut buffer : Vec<u8> = Vec::new();
let _read_count = reader.read_to_end(&mut buffer)?;
let result = cv::imgcodecs::imdecode(&cv::types::VectorOfu8::from_iter(buffer), cv::imgcodecs::IMREAD_COLOR)?;

cv::highgui::imshow(&filename, &result)?;
let _key = cv::highgui::wait_key(0)?;

Upvotes: 0

raimohanska
raimohanska

Reputation: 3405

I found out that when I change the type of the input buffer to Vec<u8> I can do this:

let original_image: Mat = imgcodecs::imdecode(&VectorOfuchar :: from_iter(buf), imgcodecs::IMREAD_COLOR)?;

Upvotes: 4

Related Questions