I need to rotate an image by either 90, 180 or 270 degrees. In OpenCV4Android I can use:
Imgproc.getRotationMatrix2D(new Point(center, center), degrees, 1);
Here's a function to rotate by any angle [-360 ... 360]
def rotate_image(image, angle):
# Grab the dimensions of the image and then determine the center
(h, w) = image.shape[:2]
(cX, cY) = (w / 2, h / 2)
# Grab the rotation matrix (applying the negative of the
# angle to rotate clockwise), then grab the sine and cosine
# (i.e., the rotation components of the matrix)
M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0)
cos = np.abs(M[0, 0])
sin = np.abs(M[0, 1])
# Compute the new bounding dimensions of the image
nW = int((h * sin) + (w * cos))
nH = int((h * cos) + (w * sin))
# Adjust the rotation matrix to take into account translation
M[0, 2] += (nW / 2) - cX
M[1, 2] += (nH / 2) - cY
# Perform the actual rotation and return the image
return cv2.warpAffine(image, M, (nW, nH))
Usage
import cv2
import numpy as np
image = cv2.imread('1.png')
rotate = rotate_image(image, angle=90)
This will rotate an image any number of degrees, using the most efficient means for multiples of 90.
void
rotate_cw(const cv::Mat& image, cv::Mat& dest, int degrees)
{
switch (degrees % 360) {
case 0:
dest = image.clone();
break;
case 90:
cv::flip(image.t(), dest, 1);
break;
case 180:
cv::flip(image, dest, -1);
break;
case 270:
cv::flip(image.t(), dest, 0);
break;
default:
cv::Mat r = cv::getRotationMatrix2D({image.cols/2.0F, image.rows/2.0F}, degrees, 1.0);
int len = std::max(image.cols, image.rows);
cv::warpAffine(image, dest, r, cv::Size(len, len));
break; //image size will change
}
}
But with opencv 3.0, this is done by just via the cv::rotate command:
cv::rotate(image, dest, e.g. cv::ROTATE_90_COUNTERCLOCKWISE);
I wrote this Python version using Numpy
only, which are much faster than using cv2.transpose()
and cv2.flip()
.
def rotate_image_90(im, angle):
if angle % 90 == 0:
angle = angle % 360
if angle == 0:
return im
elif angle == 90:
return im.transpose((1,0, 2))[:,::-1,:]
elif angle == 180:
return im[::-1,::-1,:]
elif angle == 270:
return im.transpose((1,0, 2))[::-1,:,:]
else:
raise Exception('Error')
You can rotate image using numpy rot90
function
like
def rotate_image(image,deg):
if deg ==90:
return np.rot90(image)
if deg ==180:
return np.rot90(image,2)
if deg == 270:
return np.rot90(image,-1) #Reverse 90 deg rotation
Hope this help ..
In python:
# import the necessary packages
import numpy as np
import cv2
# initialize the camera and grab a reference to the raw camera capture
vs = cv2.VideoCapture(0)
(ret, image_original) = vs.read()
image_rotated_90 = np.rot90(image_original)
image_rotated_180 = np.rot90(image_rotated_90)
# show the frame and press any key to quit the image frame
cv2.imshow("Frame", image_rotated_180)
cv2.waitKey(0)