OpenCV Python rotate image by X degrees around specific point OpenCV Python rotate image by X degrees around specific point python python

OpenCV Python rotate image by X degrees around specific point


import numpy as npimport cv2def rotate_image(image, angle):  image_center = tuple(np.array(image.shape[1::-1]) / 2)  rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0)  result = cv2.warpAffine(image, rot_mat, image.shape[1::-1], flags=cv2.INTER_LINEAR)  return result

Assuming you're using the cv2 version, that code finds the center of the image you want to rotate, calculates the transformation matrix and applies to the image.


Or much easier useSciPy

from scipy import ndimage#rotation angle in degreerotated = ndimage.rotate(image_to_rotate, 45)

seehere for more usage info.


def rotate(image, angle, center = None, scale = 1.0):    (h, w) = image.shape[:2]    if center is None:        center = (w / 2, h / 2)    # Perform the rotation    M = cv2.getRotationMatrix2D(center, angle, scale)    rotated = cv2.warpAffine(image, M, (w, h))    return rotated