Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version
struct MouseParams
{
    Mat img;
    vector<Point2f> P,Q;
};


static void onMouse( int event, int x, int y, int, void* param)
{
    // Mount back the parameters
    MouseParams* mp = (MouseParams*)param;
    Mat & img = mp->img;
    if (event == 1) // left button
    {
        Mat result;

        // remember, that you have to go clockwise,
        // starting at top-left (same order as Q)!
        mp->P.push_back(Point2f(x,y)); 

        if (mp->P.size() == 4)
        {
            Mat rot = cv::getPerspectiveTransform(mp->P,mp->Q);
            cv::warpPerspective(img, result, rot, Size(220,220));
            imshow("result",result);
        } 
        else 
        {
            result = img.clone();
            for (size_t i=0; i<mp->P.size(); i++)
            {
                circle(result,mp->P[i],3,Scalar(0,0,255));
            }
            imshow("input",result);
        }
    }
    if (event == 2) // right button, clear & try again
    {
        mp->P.clear();
        imshow("input",img);
    }
}

int main() 
{
    Mat ocv = imread("tennis.jpg");
    namedWindow("input");
    imshow("input",ocv);

    MouseParams mp;
    mp.Q.push_back(Point2f(10,10)); // 10 pixel border on all sides
    mp.Q.push_back(Point2f(210,10));
    mp.Q.push_back(Point2f(210,210));
    mp.Q.push_back(Point2f(10,210));
    mp.img = ocv;

    setMouseCallback("input", onMouse, (void*)&mp);
    waitKey();
    return 0;
}