twistedfall / opencv-rust

Rust bindings for OpenCV 3 & 4
MIT License
1.96k stars 157 forks source link

Cropping a Mat #563

Closed Dirleye closed 5 months ago

Dirleye commented 5 months ago

How would you go about cropping a Mat from a Rect?

The simplest way I can think of currently is by creating a whole new Mat and moving it back over (I haven't actually tested this and could be completely misunderstanding what assign_to_def() does):

let region: Rect = get_regeion_from_somewhere();
let mut target_mat: Mat = get_mat_from_somewhere();

let mut cropped: Mat = Mat::default();
target_mat.roi(region).unwrap().assign_to_def(&mut cropped).unwrap();
target_mat = cropped;

But that feels like too much work for something this simple. Am I missing something really obvious?

Thanks for any help.

twistedfall commented 5 months ago

If you need an independent Mat then something like this should work:

let cropped = target_mat.roi(region)?.try_clone()?;
let target_mat = cropped;
Dirleye commented 5 months ago

Ah so cloning into a new Mat is definitely needed. That is simpler though so thank you.

twistedfall commented 5 months ago

Yeah, I don't think that OpenCV supports in-place crop at all, so one or the other form of copying is required.