Skip to content

What's the ideal way to convert opencv::cv::Mat from rust to numpy.ndarray in python? #481

Open
@tubzby

Description

@tubzby

I have a cv::Mat in Rust, but want to convey the data to Python, I have checked the doc and gone to PyArray3, but it requires a Vec<Vec<Vec<T>>>, which means I have to make up the Vec manually with one copy, and from PyArray3::from_vec3 it might clone another time, that's quite inefficient, what's the proper way to do that? Is there a way to prevent data clone?

    #[test]
    fn mat_2_numpy() -> PyResult<()> {
        Python::with_gil(|py| {
            println!("in gil");
            let func: Py<PyAny> = PyModule::from_code(
                py,
                c_str!(
                    "import numpy as np
def call_np(arr):
    print(\"Shape:\", arr.shape)
                "
                ),
                c_str!(""),
                c_str!(""),
            )?
            .getattr("call_np")?
            .into();

            let img = opencv::imgcodecs::imread("/some/path/sample.jpg", 0).unwrap();
            let shape = (img.rows(), img.cols(), img.channels());

            // it requires Vec<Vec<Vec<T>>>
            let array = PyArray3::from_vec3(py, v)?;

            // pass object with Rust tuple of positional arguments
            let args = (array,);
            let engine_obj = func.call1(py, args)?;

            Ok(())
        })

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions