Ask Your Question
0

mat assignment/copy not apply to me code [closed]

asked 2020-04-15 07:19:32 -0600

pgun gravatar image

Hi,

im expecting the mat assignment method only copies the mat headers, which lead to any operation of the child matrix would lead to change of the root mat. However, this is not happening for me code. Could someone please take a look where my bug is? thanks.

My code end up only Image B displayed as grayscale picture, A and C are colored.

#include <stdio.h>
#include <opencv2/opencv.hpp>

using namespace cv;
using namespace std;

int main(int argc, char** argv )
{
    if ( argc != 2 )
    {
        printf("usage: DisplayImage.out <Image_Path>\n");
        return -1;
    }

    Mat A;

    A = imread( argv[1], IMREAD_COLOR );
    Mat B(A);
    Mat C = A;

    if ( !A.data )
    {
        printf("No image data \n");
        return -1;
    }

    cvtColor(B, B, COLOR_BGR2GRAY);
    //A = A(Range::all(), Range(1,8));
    cout<<"MAT A: \n"<<A(Range(1,5), Range(1,5))<<"\n \n";
    cout<<"MAT B: \n"<<B(Range(1,5), Range(1,5))<<"\n \n";
    cout<<"MAT C: \n"<<C(Range(1,5), Range(1,5))<<"\n \n";

    namedWindow("Display A", WINDOW_AUTOSIZE );
    imshow("Display A", A);

    namedWindow("Display B", WINDOW_AUTOSIZE );
    imshow("Display B", B);

    namedWindow("Display C", WINDOW_AUTOSIZE );
    imshow("Display C", C);
    waitKey(0);

    return 0;
}
edit retag flag offensive reopen merge delete

Closed for the following reason the question is answered, right answer was accepted by pgun
close date 2020-04-15 08:06:22.419533

1 answer

Sort by ยป oldest newest most voted
0

answered 2020-04-15 07:33:01 -0600

berak gravatar image

updated 2020-04-15 07:33:38 -0600

here's the culprit:

cvtColor(B, B, COLOR_BGR2GRAY);

you probably expected it to happen "in-place", but -- since the number of input/output pixels differ, the internal memory of B is reallocated, and it's data pointer is no more the same as A or C

in other words, all expected behaviour. (A and C still point to the very same memory)

edit flag offensive delete link more

Comments

1

Hi berak, i tried your explanation now it works as expected, thanks!

pgun gravatar imagepgun ( 2020-04-15 08:06:05 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2020-04-15 07:19:32 -0600

Seen: 120 times

Last updated: Apr 15 '20