opencv-rust icon indicating copy to clipboard operation
opencv-rust copied to clipboard

Help

Open moyang628 opened this issue 1 year ago • 1 comments

Hi,

I got a jpeg buff ,I want to convert it to opencv Mat for more image opration .

I have tried the Mat::from_raw 、Mat::new_rows_cols_with_data_def 、Mat::from_slice 、Mat::from_slice_rows_cols

it all got wrong,

now I have to save it as jpeg file and imread from it .

Is there a direct way to do that?


        let jpg_buff = std::slice::from_raw_parts(*p_data, (&*pst_frame_info).nFrameLen as usize);

        let mut file = File::create("camm.jpg").unwrap();
        let _ = file.write_all(jpg_buff);

        let mat = opencv::imgcodecs::imread_def("camm.jpg").unwrap();
        let _ = opencv::highgui::imshow("code jpeg", &mat);
        let _ = wait_key(0);
        let _ = destroy_all_windows();



moyang628 avatar Feb 09 '24 02:02 moyang628

You should use the imdecode function, but first convert the slice to Vector<u8> by calling Vector::<u8>::from_slice(jpeg_buff). If you want to avoid copying the buffer and don't mind a little bit of unsafe then instead of Vector you can use Mat:

unsafe { Mat::new_rows_cols_with_data_def(1, jpg_buff.len() as i32, u8::opencv_type(), jpg_buff.as_mut_ptr().cast::<c_void>()) }

Just make sure that you drop this Mat before you drop the jpeg_buff.

twistedfall avatar Feb 09 '24 08:02 twistedfall

thanks.

converting the slice to Vector by calling Vector::::from_slice(jpeg_buff) works

but the new_rows_cols_with_data_def dont work. the

  unsafe { Mat::new_rows_cols_with_data_def(1, jpg_buff.len() as i32, u8::opencv_type(), jpg_buff.as_mut_ptr().cast::<c_void>()) }

You should use the imdecode function, but first convert the slice to Vector<u8> by calling Vector::<u8>::from_slice(jpeg_buff). If you want to avoid copying the buffer and don't mind a little bit of unsafe then instead of Vector you can use Mat:

unsafe { Mat::new_rows_cols_with_data_def(1, jpg_buff.len() as i32, u8::opencv_type(), jpg_buff.as_mut_ptr().cast::<c_void>()) }

Just make sure that you drop this Mat before you drop the jpeg_buff.

moyang628 avatar Feb 16 '24 14:02 moyang628

When you say it doesn't work what kind of error are you getting?

twistedfall avatar Mar 17 '24 09:03 twistedfall

I'm going to close this for now with the hope that you made it work, but feel free to reopen and supply additional details if it's not the case.

twistedfall avatar Apr 15 '24 09:04 twistedfall