PyO3 / PyO3/rust-numpy

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

Open
#481 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Rust
Stars
1.4k
Forks
141
Avg merge
16m
Merged PRs (30d)
3

Description

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(())
        })

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Begin with the PyArray3::from_vec3 call and the opencv::imgcodecs::imread example in the issue. Determine whether the requested Rust cv::Mat-to-numpy.ndarray conversion can avoid the described Vec nesting and copies; done should be a documented, concrete supported approach or a clarified limitation.

Written by the indexing model from the issue text.

Assessment

Tech stack
numpy, opencv, rust
Domain
api
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.