user3927220
user3927220

Reputation:

OpenCV, dlib - image type conversion failes in a function; works outside

The logic of the program is as follows:

using namespace dlib;

int main()
{
    while (flag)
    {
        cv::Mat3b frame0;
        camera0 >> frame0;
        cv::imshow("Video0", frame0);

        array2d<rgb_pixel> img;
        assign_image(img, cv_image<bgr_pixel>(frame0));
        cv::imshow("Video0_processed", toMat(img));
        ...
    }
    ...
}

And it works just fine.

When I change it to

cv::Mat3b convert_back_and_forth(cv::Mat3b cv_img);

int main()
{
    while (flag)
    {
        cv::Mat3b frame0;
        camera0 >> frame0;
        cv::imshow("Video0", frame0);

        cv::imshow("Video0_processed", convert_back_and_forth(frame0));
        ...
    }
    ...
}

cv::Mat3b convert_back_and_forth(cv::Mat3b cv_img)
{
    array2d<rgb_pixel> img;
    assign_image(img, cv_image<bgr_pixel>(cv_img));
    return toMat(img);
}

It crashes without any error. The program simply terminates.

A version

cv::Mat3b convert_back_and_forth(cv::Mat3b cv_img);

int main()
{
    cv::Mat3b frame0;
    while (flag)
    {
        camera0 >> frame0;
        cv::imshow("Video0", frame0);
        ...
    }
    cv::imshow("Video0_processed", convert_back_and_forth(frame0));
    ...
}

cv::Mat3b convert_back_and_forth(cv::Mat3b cv_img)
{
    array2d<rgb_pixel> img;
    assign_image(img, cv_image<bgr_pixel>(cv_img));
    return toMat(img);
}

works. But of course the functionality is not the same. What is the difference between the 1st and the 2nd versions? Why the initial can possibly work whilst the latter fails?

EDIT:

I have just found that if I declare array2d<rgb_pixel> img in a global scope, the 2nd version of the program works. Nevertheless it does not really answer the question.

Upvotes: 0

Views: 1386

Answers (1)

Davis King
Davis King

Reputation: 4791

Did you read the documentation for dlib::toMat? :)

The documentation for dlib::toMat() says this:

returns an OpenCV Mat object which represents the same image as img. This is done by setting up the Mat object to point to the same memory as img. Therefore, the returned Mat object is valid only as long as pointers to the pixels in img remain valid.

Upvotes: 1

Related Questions