温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c++ - OpenCV and reading data from OutputArrays or (Mat)

c++ - OpenCV并从OutputArrays或(Mat)读取数据

发布于 2020-03-28 23:40:53

我对OpenCV自己的PnP和Rodrigues公式函数有几个问题。我认为这与cv::solvePnPRansac()

 cv::Mat w = cv::Mat::zeros(3,1,CV_32FC1);
 cv::Mat t = cv::Mat::zeros(3,1,CV_32FC1);
 std::vector<float> distortion = {0,0,0,0};

 std::vector<cv::Point3f> tmp1 = eig_vec_to_cv3(pts);
 std::vector<cv::Point2f> tmp2 =  eig_vec_to_cv2(pixels);

 cv::solvePnPRansac(tmp1, tmp2, eig_mat_2_cv(K),distortion, w, t,false, 100, 2.0f);

 cv::Mat R_ = cv::Mat::zeros(3,3,CV_32FC1);
 cv::Rodrigues(w,R_);

 std::cout<<"R_"<<std::endl;
 std::cout<<R_<<std::endl;
 std::cout<<R_.at<float>(0,0)<<std::endl;

因为std::cout<<R_<<std::endl它看起来还可以,但是却R_.at<float>(0,0)给出了垃圾箱编号,例如未分配内存。这同样适用于wt

但是,如果我这样做:

cv::Mat w_ = cv::Mat(3,1,cv_32FC1);
w.at<float>(0,0) = 0.2;
w.at<float>(0,1) = 0.4;
w.at<float>(0,2) = 0.3;

cv::Rodrigues(w_,R_);

std::cout<<"R_"<<std::endl;
std::cout<<R_<<std::endl;
std::cout<<R_.at<float>(0,0)<<std::endl;

它工作正常。

这是一个最小的(非工作)示例:

#include <opencv2/calib3d.hpp>
#include <opencv2/opencv.hpp>
#include <vector>

int main()
{
    cv::Mat w = cv::Mat(3,1,CV_32FC1);
    cv::Mat t = cv::Mat(3,1, CV_32FC1);

    std::vector<cv::Point3f> tmp1;
    std::vector<cv::Point2f> tmp2;

    for (int k = 0; k < 10; ++k)
    {
        cv::Point3f p1(0.2f+k, 0.3f-k, 7.5f-k);
        cv::Point2f p2(3.2f*k, 4.5f/k);
        tmp1.push_back(p1);
        tmp2.push_back(p2);
    }

    cv::Mat K = cv::Mat::zeros(3,3,CV_32FC1);
    K.at<float>(0,0) = 525.0;
    K.at<float>(0,2) = 234.5;
    K.at<float>(1,1) = 525;
    K.at<float>(1,2) = 312.5;
    K.at<float>(2,2) = 1.0f;

    std::vector<float> distortion = {0,0,0,0};

    cv::solvePnPRansac(tmp1, tmp2, K,distortion, w, t,false, 100, 2.0f);

    std::cout<<w<<std::endl;
    cv::Mat R = cv::Mat::zeros(3,3,CV_32FC1);
    cv::Rodrigues(w,R);
    std::cout<<R<<std::endl;

    std::cout<<R.at<float>(0,0)<<std::endl;
    return 0;
}

编译与

g++ main.cpp -I /usr/local/include/opencv4/ -o test -L /usr/local/lib/ -lopencv_calib3d -lopencv_core

查看更多

查看更多

提问者
El_Loco
被浏览
31
sgarizvi 2020-01-31 18:16

原因是该函数cv::Rodrigues创建了类型的输出矩阵CV_64FC1因此,这些值必须如下所示:

std::cout<<R.at<double>(0,0)<<std::endl;

即使我们将输出矩阵预分配为其他任何类型(例如CV_32FC1),也将通过cv::Rodriguestype 重新分配输出矩阵CV_64FC1

我认为,OpenCV文档缺乏许多功能的输入和输出类型的清晰性。在这种情况下,必须通过输出Mat::type()函数的返回值来确定输出类型

发布
问题

分享
好友

手机
浏览

扫码手机浏览