旋转cv :: Rect的中心

时间:2013-11-05 10:07:06

标签: opencv rotation rectangles

我有一张图片,我在图片上放了一个矩形。然后我旋转图像。如何在旋转的图像上获得矩形的中心?

或者我可以以某种方式旋转矩形以放置旋转图像吗?我认为在这种情况下,旋转必须沿着与用于旋转图像的点相同的点进行。

这是放置了矩形的图像。

enter image description here

这是旋转的图像。

enter image description here

以下是我用来旋转图像的代码:

cv::Mat frame, frameRotated;
frame = cv::imread("lena.png");

cv::Rect rect(225,250,150,150);
cv::rectangle(frame, rect, cv::Scalar(0,0,255),2);

int theta = 30;
double radians = theta * PI / 180.0;            

double sin = abs(std::sin(radians));
double cos = abs(std::cos(radians));

int newWidth = (int) (frame.cols * cos + frame.rows * sin);
int newHeight = (int) (frame.cols * sin + frame.rows * cos);

cv::Mat targetMat(cv::Size(newWidth, newHeight), frame.type());

int offsetX = (newWidth - frame.cols) / 2;
int offsetY = (newHeight - frame.rows) / 2;

frame.copyTo(targetMat.rowRange(offsetY, offsetY + frame.rows).colRange(offsetX, offsetX + frame.cols));

cv::Point2f src_center(targetMat.cols/2.0F, targetMat.rows/2.0F);
cv::Mat rot_mat = cv::getRotationMatrix2D(src_center, theta, 1.0);
cv::warpAffine(targetMat, frameRotated, rot_mat, targetMat.size());

imshow("frame", frame); 
imshow("rotated frame", frameRotated);  

修改

假设旋转图像中有一个点,如何使用旋转矩阵获得原始图像中的对应点?

3 个答案:

答案 0 :(得分:2)

您只需要使用rot_mat来转换rect的原始中心。我测试了下面的内容并且有效:

cv::Rect r(250, 350, 20, 30);
cv::Point2d c(r.x + r.width / 2, r.y + r.height / 2);
// c is center of rect

// get c's location in targetMat when frame is copied
c.x += offsetX;  
c.y += offsetY;


int theta = 30;
double radians = theta * M_PI / 180.0;            

cv::Point2d src_center(targetMat.cols/2.0F, targetMat.rows/2.0F);
cv::Mat rot_mat = cv::getRotationMatrix2D(src_center, theta, 1.0);

// now transform point using rot_mat
double *x = rot_mat.ptr<double>(0);
double *y = rot_mat.ptr<double>(1);
Point2d dst(x[0] * c.x + x[1] * c.y + x[2], 
            y[0] * c.x + y[1] * c.y + y[2]);
// dst is center of transformed rect

修改

要从旋转的图像转换点,您只需要反转该过程:

// undo translation
Point2d dst1(dst.x - x[2], dst.y - y[2]); 

// undo rotation
Point2d dst2(x[0] * dst1.x - x[1] * dst1.y, -y[0] * dst1.x + y[1] * dst1.y); 

// undo shift
Point2d in_unrotated_image(dst2.x - offsetX, dst2.y - offsetY); 

答案 1 :(得分:1)

您可以通过乘以旋转矩阵将源Mat中的任意点转换为旋转Mat。

如果你需要翻译X,Y并且给定T = 1,你可以通过Mat multiplication

来完成
 |  cosθ  sinθ  Tx |   | X |    | _X |
 |                 | * | Y |  = |    |
 | -sinθ  cosθ  Ty |   | 1 |    | _Y |

其中Tx和Ty是x和y的平移,参见OpenCV Doc

假设您需要在旋转的Mat中找到源Mat的中心(cent_x,cent_y)

Mat rot_mat = getRotationMatrix2D(src_center, theta, 1.0); //Find the rotation matrix 
Mat co_Ordinate = (Mat_<double>(3,1) << cent_x,cent_y,1); //Create 3x1 matrix with input co-ordinates.

Mat rst=rot_mat*co_Ordinate; // Multiply rotation matrix with input co-ordinate matrix
trans_x=(int)rst.at<double>(0,0); //First row of result will be x
trans_y=(int)rst.at<double>(1,0); //Second row of result will be y.

希望这些有用......

答案 2 :(得分:0)

我在第二个问题中解决了这个问题。

我使用了接受的答案中提供的相同代码,并创建了带负θ的旋转矩阵。