使用cv::warpAffine旋转cv::Mat并偏移目标图像

20
我正在尝试使用OpenCV的C++ API将一个1296x968像素的图像逆时针旋转90度,但是遇到了一些问题。 输入input 旋转后结果output 如您所见,旋转后的图像存在一些问题。首先,它与原始图像具有相同的大小,即使我明确地使用反向大小创建目标Mat。因此,目标图像被裁剪。
我怀疑这是由于我调用warpAffine()并传递原始Mat的大小而不是目标Mat的大小。但是我这样做是因为我遵循了这个答案,但现在我怀疑这个答案可能是错误的。所以这是我的第一个疑问/问题。
第二个问题是,warpAffine()会在某个偏移量处将数据写入目标(可能是为了将旋转后的数据复制到图像中间),这个操作会在图像周围留下可怕且大的黑色边框。 我该如何解决这些问题? 下面是源代码:
#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;
}

1
cv::warpAffine的文档中:dst-目标图像;将具有大小dsize和与src相同的类型。 - znkr
我明白了,谢谢@krynr。如果你觉得你有解决问题的方法,请随时发布答案。 - karlphillip
5个回答

27
我找到了一个解决方案,不需要使用warpAffine()。但在此之前,我需要声明一下(以便将来参考),我怀疑是正确的,你需要在调用warpAffine()时传递目标大小:
warpAffine(image, rotated_img, rot_matrix, rotated_img.size());

据我所知,这个函数造成的黑色边框(由于偏移而引起)似乎是它的标准行为。我注意到在Mac和Linux上运行的OpenCV的C接口和C++接口中都存在这个问题,使用的版本分别是2.3.1a和2.3.0。
我最终使用的解决方案比所有这些“扭曲”的方法要简单得多。您可以使用cv::transpose()cv::flip()将图像旋转90度。这是代码:
Mat src = imread(argv[1], 1);

cv::Mat dst;
cv::transpose(src, dst);
cv::flip(dst, dst, 1);

imwrite("rotated90.jpg", dst);

----I>


您可以通过各种cv::BORDER_*标志来指定边界的行为。 - Ela782
@karlphillip 这是针对方阵的。那么对于矩形矩阵呢?如何有效地旋转矩形矩阵? - Qadir Hussain

11

很多人在旋转图像或图像块时会遇到偏移等问题。因此,我发布了一种解决方案,允许您旋转图像的区域(或整个图像),并将其粘贴到另一个图像中,或者让函数计算出一张所有内容都能完美适配的图像。

// ROTATE p by R
/**
 * Rotate p according to rotation matrix (from getRotationMatrix2D()) R
 * @param R     Rotation matrix from getRotationMatrix2D()
 * @param p     Point2f to rotate
 * @return      Returns rotated coordinates in a Point2f
 */
Point2f rotPoint(const Mat &R, const Point2f &p)
{
    Point2f rp;
    rp.x = (float)(R.at<double>(0,0)*p.x + R.at<double>(0,1)*p.y + R.at<double>(0,2));
    rp.y = (float)(R.at<double>(1,0)*p.x + R.at<double>(1,1)*p.y + R.at<double>(1,2));
    return rp;
}

//COMPUTE THE SIZE NEEDED TO LOSSLESSLY STORE A ROTATED IMAGE
/**
 * Return the size needed to contain bounding box bb when rotated by R
 * @param R     Rotation matrix from getRotationMatrix2D()
 * @param bb    bounding box rectangle to be rotated by R
 * @return      Size of image(width,height) that will compleley contain bb when rotated by R
 */
Size rotatedImageBB(const Mat &R, const Rect &bb)
{
    //Rotate the rectangle coordinates
    vector<Point2f> rp;
    rp.push_back(rotPoint(R,Point2f(bb.x,bb.y)));
    rp.push_back(rotPoint(R,Point2f(bb.x + bb.width,bb.y)));
    rp.push_back(rotPoint(R,Point2f(bb.x + bb.width,bb.y+bb.height)));
    rp.push_back(rotPoint(R,Point2f(bb.x,bb.y+bb.height)));
    //Find float bounding box r
    float x = rp[0].x;
    float y = rp[0].y;
    float left = x, right = x, up = y, down = y;
    for(int i = 1; i<4; ++i)
    {
        x = rp[i].x;
        y = rp[i].y;
        if(left > x) left = x;
        if(right < x) right = x;
        if(up > y) up = y;
        if(down < y) down = y;
    }
    int w = (int)(right - left + 0.5);
    int h = (int)(down - up + 0.5);
    return Size(w,h);
}

/**
 * Rotate region "fromroi" in image "fromI" a total of "angle" degrees and put it in "toI" if toI exists.
 * If toI doesn't exist, create it such that it will hold the entire rotated region. Return toI, rotated imge
 *   This will put the rotated fromroi piece of fromI into the toI image
 *
 * @param fromI     Input image to be rotated
 * @param toI       Output image if provided, (else if &toI = 0, it will create a Mat fill it with the rotated image roi, and return it).
 * @param fromroi   roi region in fromI to be rotated.
 * @param angle     Angle in degrees to rotate
 * @return          Rotated image (you can ignore if you passed in toI
 */
Mat rotateImage(const Mat &fromI, Mat *toI, const Rect &fromroi, double angle)
{
    //CHECK STUFF
    // you should protect against bad parameters here ... omitted ...

    //MAKE OR GET THE "toI" MATRIX
    Point2f cx((float)fromroi.x + (float)fromroi.width/2.0,fromroi.y +
               (float)fromroi.height/2.0);
    Mat R = getRotationMatrix2D(cx,angle,1);
    Mat rotI;
    if(toI)
        rotI = *toI;
    else
    {
        Size rs = rotatedImageBB(R, fromroi);
        rotI.create(rs,fromI.type());
    }

    //ADJUST FOR SHIFTS
    double wdiff = (double)((cx.x - rotI.cols/2.0));
    double hdiff = (double)((cx.y - rotI.rows/2.0));
    R.at<double>(0,2) -= wdiff; //Adjust the rotation point to the middle of the dst image
    R.at<double>(1,2) -= hdiff;

    //ROTATE
    warpAffine(fromI, rotI, R, rotI.size(), INTER_CUBIC, BORDER_CONSTANT, Scalar::all(0)); 

    //& OUT
    return(rotI);
}

2
rotPointrotatedImageBB是否不再需要?只需使用cv::RotatedRect(cx,fromroi.size(),angle).boundingRect()即可。 - user362515

5
也许这能帮助到某些人。
变量如下:
img:原始图像
angle:角度
scale
dst:目标图像
int width = img.size().width, 
    height = img.size().height;
Mat rot = getRotationMatrix2D(Point2f(0,0), angle, scale)/scale; //scale later
double sinv = rot.at<double>(0,1),
       cosv = rot.at<double>(0,0);
rot.at<double>(1,2) = width*sinv;  //adjust row offset
Size dstSize(width*cosv + height*sinv, width*sinv + height*cosv);
Mat dst;
warpAffine(img, dst, rot, dstSize);
resize(dst, dst, Size(), scale, scale);  //scale now

请不要使用此代码,因为它无法处理某些图像。(错误) - Milad
@Milad 是什么错误,为什么? - Evg

4

我知道你已经找到了其他更快速的解决方案(90度旋转应该很快,而且不需要warpAffine的所有机制),但是我想为其他遇到这个问题的人解决黑边问题。

warpAffine还能做什么?目标图像的宽度大于高度,并且仿射变换只指定了旋转(围绕图像中心),没有缩放。 它确实是这样做的。 没有任何信息告诉warpAffine在那些黑色边框中应该绘制什么,因此它将它们保留为黑色。

直接物理实验:在桌子上放一张纸,画出它的轮廓(这就是当您指定要求结果与原始大小/形状相同时所做的操作)。 现在围绕其中心将该纸片旋转90度。 看看轮廓在桌子上限定的区域。 如果它是黑桌子,它会看起来与您的结果完全相同。


2

我发现一个问题,就是你在使用warpAffine时,目标图像的大小设置为image.size()而不是rotated_img.size()。然而,在变换后,它在xy方向上仍然偏移得太远了...我尝试了完全相同的变换。

[ 6.123031769111886e-17 1                     163.9999999999999;
 -1                     6.123031769111886e-17 1132;
  0                     0                     1]

我使用Matlab中的OpenCV的getRotationMatrix2D方法,它完美地工作了。我开始怀疑可能是关于warpAffine方法的一个bug...


cvWarpAffine() 在 OpenCV 2.3.1a 上的行为与以前相同。 - karlphillip
我使用了大约两周前从 SVN 主干下载的代码,问题也存在。今晚我会检查一下warpAffine代码,看看是否有什么不对劲的地方。 - mevatron
从我在其他地方看到的情况来看,这似乎是该函数的标准行为,但我不能百分之百确定。 - karlphillip
此外,OpenCV 2.3.0和2.3.1a呈现相同的行为。 - karlphillip
我给你的答案点了赞。感谢你的所有帮助!最终我使用了一种替代方法来实现这个效果,需要更少的代码行。 - karlphillip
谢谢,完全没有问题!我仍然不相信仅仅因为它已经存在一段时间就意味着它没有漏洞 :) 我会深入挖掘一下,并在发现有趣的东西时回复。 - mevatron

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接