我想将图像旋转 90 度。我的代码如下:
int main(int argc, const char * argv[]) {
Mat img = imread("/Users/chuanliu/Desktop/src4/p00.JPG");
resize(img, img, Size(1024, 683));
imwrite("/Users/chuanliu/Desktop/resize.jpg", img);
Mat dst;
Mat rot_mat = getRotationMatrix2D(Point(img.cols / 2.0, img.rows / 2.0), 90, 1);
warpAffine(img, dst, rot_mat, Size(img.rows, img.cols));
imwrite("/Users/chuanliu/Desktop/roatation.jpg", dst);
return 0;
}
But the result is like following:
Before rotation:
![enter image description here](https://i.stack.imgur.com/5syfi.jpg)
After rotation:
![enter image description here](https://i.stack.imgur.com/Drrro.jpg)
看来旋转中心出了问题。但我不认为我设置了错误的中心。有人可以告诉我出了什么问题吗?
中心根据源图像的尺寸指定Point(img.cols / 2.0, img.rows / 2.0)
但您不仅旋转图像,而且在调用时交换输出大小的宽度和高度warpAffine
:
Size(img.rows, img.cols)
所以看起来您可能需要根据输出图像坐标指定中心;例如。Point(rows/2, cols/2)
.
Update:
不,这不是解决方案。实际上有一种非常简单有效的方法可以将图像旋转 90 度:使用cv::transpose()
功能:
int main()
{
cv::Mat img = cv::imread("5syfi.jpg");
cv::Mat img_rotated;
cv::transpose(img, img_rotated);
cv::imwrite("out.jpg", img_rotated);
return 0;
}
使用组合cv::transpose()
(旋转)和cv::flip()
(垂直和水平镜像)您可以非常快速地执行 90、180 和 270 度旋转。
Using warpAffine()
更灵活,但计算成本也更高(即更慢)。因此,如果您只需要旋转 90 度的倍数,请使用cv::transpose
。如果需要旋转任意角度,请使用warpAffine/warpPerspective
功能。 @Micka 的回答给出了如何做到这一点的一个很好的例子。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)