rust-ndarray / ndarray

ndarray: an N-dimensional array with array views, multidimensional slicing, and efficient operations

Home Page:https://docs.rs/ndarray/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Access to raw data slice

kotx opened this issue · comments

commented

Would it be feasible to implement something like into_raw_vec but returning a read-only view of the internal data?

This way we don't need to clone the array before conversion.

For example, I'm using this StackOverflow answer to convert an array to an image.
To do this without consuming the array I need to clone it and then pass it to array_to_image.
but RgbImage::from_raw technically only needs a slice, so it would be better to just not clone the array, which is probably(?) a lot more expensive (I want to call array_to_image many times, after modifying the array).

commented

Have you considered if as_slice_memory_order works for this?

commented

Have you considered if as_slice_memory_order works for this?

@bluss Seems to produce the same output and resolves the issue, but not sure what differs internally. Is it a suitable replacement/should I close this issue?

into_raw_vec consumes the array. It gives you a Vec that you own, so you can take a slice of it after, if you want.

let raw = arr.into_raw_vec();
RgbImage::from_raw(width as u32, height as u32, raw.as_slice())
// you can still use `raw`

Since you do not want to consume the array, as_slice_memory_order is perfect for your need. It gives you a readonly slice. So, yes, it's a suitable replacement and you can close this issue. The rest is more a programming/rust question than a ndarray question.

I want to call array_to_image many times, after modifying the array

If you need to keep the original version of the array, then you don't need to clone, no? Otherwise, arr will be the "sum" of all your modifications (which mighe be what you want, I don't know)

for all modifications that you want to do {
    let mut arr = arr.clone();
    // Apply the modification
    // ?
    let raw = arr.as_slice_memory_order().expect("Array is not contiguous");
}
commented

yes, it's a suitable replacement and you can close this issue.

Got it, thanks.

If you need to keep the original version of the array, then you don't need to clone, no? Otherwise, arr will be the "sum" of all your modifications (which mighe be what you want, I don't know)

for all modifications that you want to do {
    let mut arr = arr.clone();
    // Apply the modification
    // ?
    let raw = arr.as_slice_memory_order().expect("Array is not contiguous");
}

Well, I need to modify the original array, and extract it as an image, many times and in any order.
Basically many clients will modify the array, but a client can request an image at any time (but without consuming the array), if that makes sense.

Thanks for the help!