簡體   English   中英

通過warpAffine(opencv,c ++)在旋轉圖像后獲取cv :: rect的新位置

[英]get new location of cv::rect after rotation image by warpAffine (opencv , c++)

我想通過使用以下代碼旋轉圖像后獲得cv :: rect(ROI)的新位置:

cv::Point2f center(image.cols/2.0, image.rows/2.0);

cv::Rect ROI = cv::Rect(100,200,50,100);

cv::Mat rot = cv::getRotationMatrix2D(center, angle, 1.0);
cv::Rect bbox = cv::RotatedRect(center,image.size(), angle).boundingRect();

rot.at<double>(0,2) += bbox.width/2.0 - center.x;
rot.at<double>(1,2) += bbox.height/2.0 - center.y;


cv::warpAffine(image, image, rot, bbox.size(),cv::INTER_LINEAR,cv::BORDER_CONSTANT,
               cv::Scalar(255, 255, 255));

我該怎么辦?

由於具有旋轉矩陣,因此可以使用cv::transform函數旋轉ROI矩形。 首先,您需要該矩形的點數組。

vector<Point2f> roi_points = {
        {roi.x,             roi.y},
        {roi.x + roi.width, roi.y},
        {roi.x + roi.width, roi.y + roi.height},
        {roi.x,             roi.y + roi.height}
};

然后,您可以使用cv::transform

vector<Point2f> rot_roi_points;
transform(roi_points, rot_roi_points, rot);

這樣, rot_roi_points保存轉換后的矩形的點。

在此處輸入圖片說明 ==> 在此處輸入圖片說明

為了獲得cv :: rect(ROI)的新位置,您必須使用以下函數來變換其每個角:

cv::Point2f Convert(const cv::Point2f & p, const cv::Mat & t)
{
    float x = p.x*t.at<double>((0, 0) + p.y*t.at<double>((0, 1) + t.at<double>((0, 2); 
    float y = p.x*t.at<double>((1, 0) + p.y*t.at<double>((1, 1) + t.at<double>((1, 2); 
    return cv::Point2f(x, y);
}

轉換矩陣與用於圖像旋轉的矩陣相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM