Easiest way to rotate by 90 degrees an image using OpenCV?
What is the best way (in c/c++) to rotate an IplImage/cv::Mat by 90 degrees? I would assume that there must be something better than transforming it using a matrix, but I can't seem to find anything other than that in the API and online.
Solution 1:
As of OpenCV3.2, life just got a bit easier, you can now rotate an image in a single line of code:
cv::rotate(image, image, cv::ROTATE_90_CLOCKWISE);
For the direction you can choose any of the following:
ROTATE_90_CLOCKWISE
ROTATE_180
ROTATE_90_COUNTERCLOCKWISE
Solution 2:
Rotation is a composition of a transpose and a flip.
Which in OpenCV can be written like this (Python example below):
img = cv.LoadImage("path_to_image.jpg")
timg = cv.CreateImage((img.height,img.width), img.depth, img.channels) # transposed image
# rotate counter-clockwise
cv.Transpose(img,timg)
cv.Flip(timg,timg,flipMode=0)
cv.SaveImage("rotated_counter_clockwise.jpg", timg)
# rotate clockwise
cv.Transpose(img,timg)
cv.Flip(timg,timg,flipMode=1)
cv.SaveImage("rotated_clockwise.jpg", timg)
Solution 3:
Here is my python cv2
implementation:
import cv2
img=cv2.imread("path_to_image.jpg")
# rotate ccw
out=cv2.transpose(img)
out=cv2.flip(out,flipCode=0)
# rotate cw
out=cv2.transpose(img)
out=cv2.flip(out,flipCode=1)
cv2.imwrite("rotated.jpg", out)
Solution 4:
Update for transposition:
You should use cvTranspose()
or cv::transpose()
because (as you rightly pointed out) it's more efficient. Again, I recommend upgrading to OpenCV2.0 since most of the cvXXX
functions just convert IplImage*
structures to Mat
objects (no deep copies). If you stored the image in a Mat
object, Mat.t()
would return the transpose.
Any rotation:
You should use cvWarpAffine by defining the rotation matrix in the general framework of the transformation matrix. I would highly recommend upgrading to OpenCV2.0 which has several features as well as a Mat
class which encapsulates matrices and images. With 2.0 you can use warpAffine to the above.