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

Posted

技术标签:

【中文标题】如何将二维笛卡尔坐标数组转换为 OpenCV 输入数组?【英文标题】:How do I convert an array of two-dimensional Cartesian coordinates to an OpenCV input array? 【发布时间】:2021-01-18 22:55:04 【问题描述】:

最初,我尝试使用 Rust OpenCV bindings (Crate opencv 0.48.0) 来实现 OpenCV Basic Drawing 示例。 但是,我被卡住了。

我想用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"]

【问题讨论】:

你应该可以做core::Vector::from(vec![core::Point2i::new(100, 50), ...])或类似的。 【参考方案1】:

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

我可以用opencv::types::VectorOfPoint 定义顶点,实现opencv::core::ToInputArray 特征:

let pts = types::VectorOfPoint::from(vec![
    core::Pointx: 100, y: 50,
    core::Pointx: 50, y: 150,
    core::Pointx: 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::Pointx: 100, y: 50,
        core::Pointx: 50, y: 150,
        core::Pointx: 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();

【讨论】:

酷 - 干得好。并感谢您的回馈。 最后,在 rust 中使用 OpenCV 完美无缺

以上是关于如何将二维笛卡尔坐标数组转换为 OpenCV 输入数组?的主要内容,如果未能解决你的问题,请参考以下文章

将二维坐标转换为一维数组

OpenCV中的霍夫线变换和霍夫圆变换

在opencv中,如何将二维数组转化为一副图像进行显示?

OpenCV Mat 到 alglib 真实二维数组的转换

如何将 C++ 数组转换为 opencv Mat

opencv由二维数组转换图像问题