Vion
Vion

Reputation: 569

OpenCV: Find original coordinates of a rotated point

I have the following problem. I'm searching for eyes within an image using HaarClassifiers. Due to the rotation of the head I'm trying to find eyes within different angles. For that, I rotate the image by different angles. For rotating the frame, I use the code (written in C++):

    Point2i rotCenter;
    rotCenter.x = scaledFrame.cols / 2;
    rotCenter.y = scaledFrame.rows / 2;

    Mat rotationMatrix = getRotationMatrix2D(rotCenter, angle, 1);

    warpAffine(scaledFrame, scaledFrame, rotationMatrix, Size(scaledFrame.cols, scaledFrame.rows));

This works fine and I am able to extract two ROI Rectangles for the eyes. So, I have the top/left coordinates of each ROI as well as their width and height. However, these coordinates are the coordinates in the rotated image. I don't know how I can backproject this rectangle onto the original frame.

Assuming I have the obtaind eye pair rois for the unscaled frame (full_image), but still roated.

eye0_roi and eye1_roi

How can I rotate them back, such that they map their correct position?

Best regards, Andre

Upvotes: 3

Views: 1806

Answers (1)

tidy
tidy

Reputation: 5057

You can use the invertAffineTransform to get the inverse matrix and use this matrix to rotate point back:

Mat RotateImg(const Mat& img, double angle, Mat& invertMat)
{
    Point center = Point( img.cols/2, img.rows/2);
    double scale = 1;

    Mat warpMat = getRotationMatrix2D( center, angle, scale );
    Mat dst = Mat(img.size(), CV_8U, Scalar(128));
    warpAffine( img, dst, warpMat, img.size(), 1, 0, Scalar(255, 255, 255));
    invertAffineTransform(warpMat, invertMat);
    return dst;
}

Point RotateBackPoint(const Point& dstPoint, const Mat& invertMat)
{
    cv::Point orgPoint;
    orgPoint.x = invertMat.at<double>(0,0)*dstPoint.x + invertMat.at<double>(0,1)*dstPoint.y + invertMat.at<double>(0,2);
    orgPoint.y = invertMat.at<double>(1,0)*dstPoint.x + invertMat.at<double>(1,1)*dstPoint.y + invertMat.at<double>(1,2);
    return orgPoint;
}

Upvotes: 5

Related Questions