Skip to content

How to own a part of array, just like what OpenCV does? #1097

Closed

Description

@fzyzcjy

Hi thanks for the lib! I want to own a part of array, just like what OpenCV does. Consider the (simplified) code:

fn read_and_crop_image() -> ??? {
  let big_image: Array2<u8> = read_the_image();
  let cropped = big_image.slice(s![0..3000, 0..4000]);
  cropped // ERROR!!
}

However it errors, since ArrayView should not outlive the Array it belongs to. I have tried ArcArray but it does not seem to support .slice() as well.

With OpenCV I can do:

fn read_and_crop_image() -> Mat {
  let big_image: Mat = read_the_image();
  let cropped = Mat::roi([0..3000, 0..4000], big_image);
  cropped // no problem, it is another Mat, and underlying it is reference counting
}

Activity

  1. jturner314 commented on Oct 29, 2021

    @jturner314
    Member

    You could use .slice_move(), .slice_collapse(), or other similar methods, and return an owned Array2<u8>, e.g.:

    fn read_and_crop_image() -> Array2<u8> {
        let big_image: Array2<u8> = read_the_image();
        let cropped = big_image.slice_move(s![0..3000, 0..4000]);
        cropped
    }

    You could also do something similar with ArcArray. The key is to return an owned array type (Array or ArcArray), rather than a view of an array which will be dropped at the end of the function body.

    Another option is to copy the relevant portion, which may be beneficial if the original image is much larger than the cropped portion:

    fn read_and_crop_image() -> Array2<u8> {
        let big_image: Array2<u8> = read_the_image();
        let cropped = big_image.slice(s![0..3000, 0..4000]).to_owned();
        cropped
    }
  2. fzyzcjy commented on Oct 29, 2021

    @fzyzcjy
    Author

    Thank you!

  3. locked and limited conversation to collaborators on Oct 29, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions