0

I am using this method to rotate a cvMat, whenever I run it I get back a rotated image however there is a lot of deadspace below it.

void rotate(cv::Mat& src, double angle, cv::Mat& dst)
{
    int len = std::max(src.cols, src.rows);
    cv::Point2f pt(len/2., len/2.);
    cv::Mat r = cv::getRotationMatrix2D(pt, angle, 1.0);

    cv::warpAffine(src, dst, r, cv::Size(len, len));

}

When given this image:

enter image description here

I get this image:

enter image description here

The image has been rotated but as you can see some extra pixels have been added, how can I only rotate the original image and not add any extra pixels?

Method call:

rotate(src, skew, res); res being dst.

Clip
  • 3,018
  • 8
  • 42
  • 77

2 Answers2

2

You have to define the output image size while using warpAffine transform. Here you are defining the size as cv::Size(len, len) where len is max of height and width.

cv::warpAffine(src, dst, r, cv::Size(len, len));

Define/calculate the size of the final image accordingly.

Manfred Radlwimmer
  • 13,257
  • 13
  • 53
  • 62
Manish Agrawal
  • 10,958
  • 6
  • 44
  • 76
  • Ok I replaced `cv::Size(len, len))` with `src.size()` and have been getting good results. This is what I am getting now: http://i.imgur.com/W6T3yoJ.png How can I avoid adding the black area? Thanks – Clip Apr 18 '14 at 05:36
2

As mayank-baddi said you have to use output image size same as the input to resolve this, and my answer is based on your comment above How can I avoid adding the black area? after wrapAffine,

So you have to do,

  • Create white image little bigger than your source, and it will depend on your skew angle, here I used 50 pixel.

    int extend=50;
    Mat tmp(src.rows+2*extend,src.cols+2*extend,src.type(),Scalar::all(255));
    
  • Copy the source to above using ROI

    Rect ROI(extend,extend,src.cols,src.rows);
    src.copyTo(tmp(ROI));
    
  • Now rotate tmp instead of src

    rotate(tmp, skew, res); res being dst.
    
  • Crop back the final image from rotated result using the same ROI.

     Mat crop=res(ROI);  
     imshow("crop",crop);
    

enter image description here

Haris
  • 13,645
  • 12
  • 90
  • 121
  • Since `extend` is based off skew angle how could I make it work for different skew angles? – Clip Apr 18 '14 at 17:39
  • @Nick See the answer here http://stackoverflow.com/questions/22041699/rotate-an-image-without-cropping-in-opencv-in-c/22042434#22042434 – Haris Apr 18 '14 at 18:27