如何将二维笛卡尔坐标数组转换为 OpenCV 输入数组?

How do I convert an array of two-dimensional Cartesian coordinates to an OpenCV input array?

最初,我尝试实现 OpenCV Basic Drawing example with rust using Rust OpenCV bindings (Crate opencv 0.48.0)。 然而,我被卡住了。

我想用 opencv::imgproc::polylines 画一个封闭的多边形。 多边形的顶点由二维笛卡尔坐标数组给出。 我需要将这些点传递给 &dyn opencv::core::ToInputArray 类型的函数的第二个参数。 这就是我挣扎的地方。如何将顶点数组转换为 opencv::core::ToInputArray 类型的参数?

let pts = [[100, 50], [50, 150], [150, 150]];

imgproc::polylines(
        &mut image, 
        ???, <-- "pts" have to go here   
        true, 
        core::Scalar::from([0.0, 0.0, 255.0, 255.0]), 
        1, 8, 0).unwrap();

最小示例

use opencv::{core, imgproc, highgui};

fn main() {
    let mut image : core::Mat = core::Mat::new_rows_cols_with_default(
        200, 200, core::CV_8UC4, core::Scalar::from([0.0, 0.0, 0.0, 0.0])).unwrap();

    // draw yellow quad
    imgproc::rectangle(
        &mut image, core::Rect {x: 50, y: 50, width: 100, height: 100},
        core::Scalar::from([0.0, 255.0, 255.0, 255.0]), -1, 8, 0).unwrap();

    // should draw red triangle -> causes error (of course)
    /*
    let pts = [[100, 50], [50, 150], [150, 150]];
    imgproc::polylines(
        &mut image, 
        &pts, 
        true, 
        core::Scalar::from([0.0, 0.0, 255.0, 255.0]), 
        1, 8, 0).unwrap();
    */

    highgui::imshow("", &image).unwrap();
    highgui::wait_key(0).unwrap();
}
[dependencies]
opencv = {version = "0.48.0", features = ["buildtime-bindgen"]}

我在@kmdreko 的评论的帮助下找到了解决方案。

我可以用 opencv::types::VectorOfPoint, that implements an opencv::core::ToInputArray 特征定义顶点:

let pts = types::VectorOfPoint::from(vec![
    core::Point{x: 100, y: 50},
    core::Point{x: 50, y: 150},
    core::Point{x: 150, y: 150}]
);

完整示例:

use opencv::{core, types, imgproc, highgui};

fn main() {
    let mut image : core::Mat = core::Mat::new_rows_cols_with_default(
        200, 200, core::CV_8UC4, core::Scalar::from([0.0, 0.0, 0.0, 0.0])).unwrap();

    let pts = types::VectorOfPoint::from(vec![
        core::Point{x: 100, y: 50},
        core::Point{x: 50, y: 150},
        core::Point{x: 150, y: 150}]
    );

    imgproc::polylines(
        &mut image, 
        &pts, 
        true, 
        core::Scalar::from([0.0, 0.0, 255.0, 255.0]), 
        1, 8, 0).unwrap();
    
    highgui::imshow("", &image).unwrap();
    highgui::wait_key(0).unwrap();
}