Ask Your Question

How to copy cv::Mat *img to cv::Mat img

asked 2020-03-04 00:59:28 -0600

prabhakarMP gravatar image

updated 2020-03-04 01:02:15 -0600

Hi I have started exploring something in Darkent YOLO object detection. Where Video capture is done as below

mat_cv* get_capture_frame_cv(cap_cv *cap) {
    cv::Mat *mat = new cv::Mat();
    try {
        if (cap) {
            cv::VideoCapture &cpp_cap = *(cv::VideoCapture *)cap;
            if (cpp_cap.isOpened())
                cpp_cap >> *mat;
            else std::cout << " Video-stream stopped! \n";
        else cerr << " cv::VideoCapture isn't created \n";
    catch (...) {
        std::cout << " OpenCV exception: Video-stream stoped! \n";
    return (mat_cv *)mat;

Where cpp_cap >> *mat; catures the frame where I want to take Perspective and returns output at return (mat_cv *)mat;

Here I stuck how to pass cv::Mat *mat to warpPerspective function where its input is Mat type. Please help me.

Regards, Prabhakar M

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2020-03-04 01:35:04 -0600

berak gravatar image

cv::Mat is already a refcounted smart pointer, if you pass around pointers to that, you defeat its purpose.

please do NOT use any raw pointers or new here, and pass objects by reference:

Mat get_capture_frame_cv(cv::VideoCapture &cpp_ca)
    cv::Mat mat; // NO new !
    if (cpp_cap.isOpened())
         cpp_cap >> mat;
    else cerr << " cv::VideoCapture isn't open \n";
    if (mat.empty()) {
          cerr << " Video-stream stopped! \n";
    return mat;

VideoCapture cap(0); // 1st webcam
Mat img = get_capture_frame_cv(cap);
edit flag offensive delete link more


@berak Hi Berak Thanks for your suggestion. Actually that function used in Darknet YOLO object detection I cant change that because they used that data type in some other function also. It will be helpful if I can copy data cv::Mat *img to cv::Mat img.

prabhakarMP gravatar imageprabhakarMP ( 2020-03-04 02:13:01 -0600 )edit

function used in Darknet YOLO object detection

only in the demo code (which tries to be C, not c++), and you don't have to use it (it won't even compile with latest opencv)

please don't insist on "doing the wrong thing"

It will be helpful if I can copy data cv::Mat *img to cv::Mat img.

lookup "dereferencing a pointer", that's very basic c/c++

berak gravatar imageberak ( 2020-03-04 02:50:13 -0600 )edit

@berak Thank you Berak, I got some problem even after deference the pointer so I thought I am missing something. In Darknet YOLO I should run demo code for Camera access. If I am wrong please help me to correct it

prabhakarMP gravatar imageprabhakarMP ( 2020-03-04 03:01:17 -0600 )edit

Question Tools

1 follower


Asked: 2020-03-04 00:59:28 -0600

Seen: 911 times

Last updated: Mar 04 '20