Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV - image getting blurred when rotating with warpAffine

I'm using openCv's warpAffine() function to rotate an image with this code-

void rotateImage(const Mat &src, Mat &dest, double angle)
{
    cv::Point2f point(src.cols/2, src.rows/2);

    Mat rotationMatrix = cv::getRotationMatrix2D(point, angle, 1.0);

    cv::warpAffine(src, dest, rotationMatrix, cv::Size(src.cols, src.rows));
}

It works fine if I rotate the image with some angle multiple of 90 (in degrees) but severly blurs the image with any arbitrary rotation angle.

eg- the original image

enter image description here

After rotating by 90 degree multiple times-

enter image description here

After rotating by 30 degree multiple times-

enter image description here

So is there any way I can rotate the image by any arbitrary angle and avoid the caused blur?

like image 726
Harshil Sharma Avatar asked Jul 25 '14 10:07

Harshil Sharma


People also ask

What does cv2 warpAffine do?

OpenCV provides a function cv2. warpAffine() that applies an affine transformation to an image. You just need to provide the transformation matrix (M). The basic syntax for the function is given below.

How do I rotate an image without cropping in OpenCV?

You can enter rotateCode= 0 or 1 or 2. Depends on your rotation. It's gonna give you 0 or 90 or 180 or 270 angles. Save this answer.

How do I rotate an image 90 degrees in OpenCV?

We can rotate a given image using OpenCV in two ways. One is using the cv. rotate() function and other is using cv2. getRotationMatrix2D() function.


1 Answers

You could try to use the flags option to see the result of different interpolation methods:

INTER_NEAREST - a nearest-neighbor interpolation

INTER_LINEAR - a bilinear interpolation (default)

INTER_AREA - resampling using pixel area relation. It may be a preferred method for image decimation, as it gives moire’-free results. But when the image is zoomed, it is similar to the INTER_NEAREST method.

INTER_CUBIC - a bicubic interpolation over 4x4 pixel neighborhood

INTER_LANCZOS4 - a Lanczos interpolation over 8x8 pixel neighborhood

For example:

cv::warpAffine(src, dest, rotationMatrix, cv::Size(src.cols, src.rows),cv::INTER_CUBIC);

You will always lose some quality though, because of the interpolation. It is better not to do multiple warps on the same image after each other.

like image 189
diip_thomas Avatar answered Oct 02 '22 09:10

diip_thomas