使用 cv::warpAffine 旋转 cv::Mat 偏移目标图像
我正在尝试使用 OpenCV 的 C++ API 将 1296x968 图像90 度旋转我面临一些问题.
I'm trying to rotate a 1296x968 image by 90 degrees using the C++ API of OpenCV and I'm facing a few problems.
输入:
轮换:
如您所见,旋转后的图像存在一些问题.首先,它具有与原始大小相同的大小,尽管我专门创建了目标 Mat
与原始大小相反的大小.结果,目标图像被裁剪.
As you can see, the rotated image has a few problems. First, it has the same size of the original, even though I specifically create the destination Mat
with the inverted size of the original. As a result, the destination image gets cropped.
我怀疑这是因为我正在调用 warpAffine()
并传递原始 Mat
的大小而不是目标 Mat
的大小代码>.但我这样做是因为 我关注了 这个答案,但现在我怀疑答案可能是错误的.所以这是我的第一个疑问/问题.
I suspect this is happening because I'm calling warpAffine()
and passing the size of the original Mat
instead of the size of destination Mat
. But I'm doing this because I followed this answer, but now I suspect that the answer may be wrong. So this is my first doubt/problem.
第二个,是 warpAffine()
是 在某个偏移量处写入目的地(可能是将旋转后的数据复制到图像的中间)并且这个操作会在图像周围留下可怕的黑色大边框.
The second, is that warpAffine()
is writing to the destination at a certain offset (probably to copy the rotated data to the middle of the image) and this operation leaves a horrible and large black border around the image.
如何解决这些问题?
我在下面分享源代码:
#include <cv.h>
#include <highgui.h>
#include <iostream>
using namespace cv;
using namespace std;
void rotate(Mat& image, double angle)
{
Point2f src_center(image.cols/2.0F, image.rows/2.0F);
Mat rot_matrix = getRotationMatrix2D(src_center, angle, 1.0);
Mat rotated_img(Size(image.size().height, image.size().width), image.type());
warpAffine(image, rotated_img, rot_matrix, image.size());
imwrite("rotated.jpg", rotated_img);
}
int main(int argc, char* argv[])
{
Mat orig_image = imread(argv[1], 1);
if (orig_image.empty())
{
cout << "!!! Couldn't load " << argv[1] << endl;
return -1;
}
rotate(orig_image, 90);
return 0;
}
推荐答案
我找到了一个解决方案,不涉及 warpAffine()
.
I've found a solution that doesn't involve warpAffine()
.
但在此之前,我需要说明(以供将来参考)我的怀疑是正确的,您需要在调用 warpAffine()
:
But before that, I need to state (for future references) that my suspicion was right, you needed to pass the size of the destination when calling warpAffine()
:
warpAffine(image, rotated_img, rot_matrix, rotated_img.size());
据我所知,这个函数绘制的黑色边框(由偏移量引起)似乎是它的标准行为.我注意到 C 接口以及在 Mac 和 Linux 上运行的 OpenCV 的 C++ 接口,使用版本 2.3.1a 和 2.3.0.
As far as I can tell, the black border (caused by writing at an offset) drawed by this function seems to be it's standard behavior. I've noticed this with the C interface and also with the C++ interface of OpenCV running on Mac and Linux, using the versions 2.3.1a and 2.3.0.
我最终使用的解决方案比所有这些 扭曲的东西简单得多.您可以使用 cv::transpose()
和 cv::flip()
将图像旋转 90 度.这里是:
The solution I ended up using is much simpler than all this warp thing. You can use cv::transpose()
and cv::flip()
to rotate an image by 90 degrees. Here it is:
Mat src = imread(argv[1], 1);
cv::Mat dst;
cv::transpose(src, dst);
cv::flip(dst, dst, 1);
imwrite("rotated90.jpg", dst);
----I>
相关文章