Repository navigation
Replies: 1 comment
|
Both directions in the snippet copy the pixel data: For NumPy → Rust processing during a function call, accept a borrowed array and let the algorithm operate on a view: use numpy::PyReadonlyArray3;
use pyo3::{exceptions::PyValueError, prelude::*};
#[pyfunction]
fn sum_rgb(image: PyReadonlyArray3<'_, u8>) -> PyResult<u64> {
let view = image.as_array();
if view.shape()[2] != 3 {
return Err(PyValueError::new_err("expected H x W x 3"));
}
Ok(view.iter().map(|&x| u64::from(x)).sum())
}That also handles strided arrays. An algorithm requiring contiguous interleaved pixels can use For Rust → NumPy, if you have an owned use numpy::{ndarray::Array3, IntoPyArray, PyArray3};
fn owned_rgb<'py>(
py: Python<'py>, pixels: Vec<u8>, height: usize, width: usize,
) -> PyResult<Bound<'py, PyArray3<u8>>> {
let image = Array3::from_shape_vec((height, width, 3), pixels)
.map_err(|e| PyValueError::new_err(e.to_string()))?;
Ok(image.into_pyarray(py))
}This is an ownership-transfer example, not an Arrow-buffer-to-Vec conversion. At the Kornia revision you linked, storage wraps a I compiled and exercised the examples above with numpy 0.30.0 / PyO3 0.30.1, including pointer equality across the owned transfer, strided inputs, wrong dimensions/dtype, and channel validation. They use the current API; the 2024 Kornia binding would need version-appropriate names. Ownership-transfer implementation. Prepared and tested with Codex; the complete Kornia/Arrow wrapper was not implemented here. |
Uh oh!
There was an error while loading. Please reload this page.
HI! I'm running kornia-rs a Rust computer vision library in which i recently moved away from the
ndarraycrate to represent our internalTensorandImagestructures towards supporting the arrow-rs project.I have implemented the following approach in order to provide minimal python support to interact with numpy. And I'm looking for adivse wether this could be most efficient / elegant way to achieve zero-copy conversions. Thanks in advance !
All reactions