Search code examples
c++imageopencvimage-processingaffinetransform

How to use warpAffine function in OpenCV C++


I need to warp an image by using an affine transformation. The error I get is that the "code has crashed".

Can anyone tell me what is wrong with my code?

Mat imgAffine, image, par;
image = imread("/media/sf_vbox_share/ubuntushare/board.jpg",1);

par.at<double>(0,0)=  1.01121;  //p1
par.at<double>(1,0)=  0.21067;  //p2;
par.at<double>(0,1)= -89.69693; //p3;
par.at<double>(1,1)= - 0.11557; //p4;
par.at<double>(0,2)= 1.44982;   //p5;
par.at<double>(1,2)= -193.66149;//p6;

imgAffine = Mat::zeros(image.rows, image.cols, image.type());
warpAffine(image,imgAffine,par, image.size(),INTER_LINEAR);
namedWindow("image",WINDOW_AUTOSIZE);
imshow("image",imgAffine);
cvWaitKey(0);

Solution

  • par is undefined in size so when trying to write elements to it, it is most likely giving you segmentation faults. Try allocating the memory for it first before setting its elements:

    // Your code
    Mat imgAffine, image, par;
    image = imread ("/media/sf_vbox_share/ubuntushare/board.jpg",1);
    
    // New code
    par = Mat(2, 3, CV_64FC1); // Allocate memory
    
    // Rest of your code
    par.at<double>(0,0)=  1.01121;  //p1
    par.at<double>(1,0)=  0.21067 ;  //p2;
    par.at<double>(0,1)= -89.69693; //p3;
    par.at<double>(1,1)= - 0.11557;  //p4;
    par.at<double>(0,2)= 1.44982;   //p5;
    par.at<double>(1,2)= -193.66149;//p6;
    //
    // ....
    // ....
    

    Alternatively, you can use the constructor of cv::Mat when declaring par, so at the beginning of the code:

    Mat imgAffine, image;
    Mat par(2, 3, CV_64FC1);
    
    // Rest of your code
    image = imread ("/media/sf_vbox_share/ubuntushare/board.jpg",1);
    
    //
    // ....
    // ....