OpenCV:按一定角度旋转点:溶液中的偏移/偏移

OpenCV: Rotate points by an angle: Offset/shift in solution

本文关键字:偏移 旋转 OpenCV      更新时间:2023-10-16

>我正在尝试按用户定义的角度旋转矢量中的一组点,并在 SO 找到了解决方案。 在下面的代码中,输出图像的尺寸和旋转角度(45 度(是正确的,但点的位置似乎发生了偏移。 有人可以给我小费,问题是什么? 编辑:请参阅附加的图片,其中生成的线正确旋转,但结果不是从 (0,0((左上角(开始。

生成行 旋转线

cv::Point rotate2d(const cv::Point& inPoint, const double& angRad)
{
cv::Point outPoint;
//CW rotation
outPoint.x = std::cos(angRad)*inPoint.x - std::sin(angRad)*inPoint.y;
outPoint.y = std::sin(angRad)*inPoint.x + std::cos(angRad)*inPoint.y;
return outPoint;
}
cv::Point rotatePoint(const cv::Point& inPoint, const cv::Point& center, const double& angRad)
{
return rotate2d(inPoint - center, angRad) + center;
}

int main( int, char** argv )
{
// Create an dark Image with a gray line in the middle
Mat img = Mat(83, 500, CV_8U);
img = Scalar(0);
vector<Point> pointsModel;
for ( int i = 0; i<500; i++)
{
pointsModel.push_back(Point(i , 41));
}
for ( int i=0; i<pointsModel.size(); i++)
{
circle(img, pointsModel[i], 1, Scalar(120,120,120), 1, LINE_8, 0);
}
imshow("Points", img);
// Rotate Points
vector<Point> rotatedPoints;
Point tmpPoint;
cv::Point pt( img.cols/2.0, img.rows/2.0 );
for ( int i=0; i<pointsModel.size(); i++)
{
tmpPoint = rotatePoint(pointsModel[i] , pt , 0.7854);
rotatedPoints.push_back(tmpPoint);
}
Rect bb = boundingRect(rotatedPoints);
cout << bb;
Mat rotatedImg = Mat(bb.height, bb.width, img.type());
rotatedImg = Scalar(0);
for (int i=0; i<rotatedPoints.size(); i++ )
{
circle(rotatedImg, rotatedPoints[i], 1, Scalar(120,120,120), 1, LINE_8, 0);
}
imshow("Points Rotated", rotatedImg);
waitKey();
return 0;
}

在这两行上:

Rect bb = boundingRect(rotatedPoints);
Mat rotatedImg = Mat(bb.height, bb.width, img.type());

将新图像尺寸设置为bb的大小。但是bb本身有一个平移偏移,您在继续变换点时没有考虑到这一点;因此,等效地,新视口本身是偏移的。

相反,您可以做的是扩展原始图像以适应bb,即如下所示:

Mat rotatedImg(std::max(img.width(), bb.x + bb.width), std::max(img.height(), bb.y + bb.height), img.type());