Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV Python rotate image by X degrees around specific point

I'm having a hard time finding examples for rotating an image around a specific point by a specific (often very small) angle in Python using OpenCV.

This is what I have so far, but it produces a very strange resulting image, but it is rotated somewhat:

def rotateImage( image, angle ):
    if image != None:
        dst_image = cv.CloneImage( image )

        rotate_around = (0,0)
        transl = cv.CreateMat(2, 3, cv.CV_32FC1 )

        matrix = cv.GetRotationMatrix2D( rotate_around, angle, 1.0, transl )
        cv.GetQuadrangleSubPix( image, dst_image, transl )
        cv.GetRectSubPix( dst_image, image, rotate_around )

    return dst_image
like image 876
Mike Avatar asked Jan 27 '12 23:01

Mike


People also ask

How do I rotate an image in 90 degrees OpenCV?

We can use the cv2. ROTATE_90_COUNTERCLOCKWISE to rotate the image to 90 degrees counterclockwise or 270 degrees clockwise. These are the only three angles to rotate an image using the rotate() function.


3 Answers

import numpy as np
import cv2

def 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.

like image 73
Alex Rodrigues Avatar answered Oct 12 '22 15:10

Alex Rodrigues


Or much easier use SciPy

from scipy import ndimage

#rotation angle in degree
rotated = ndimage.rotate(image_to_rotate, 45)

see here for more usage info.

like image 27
fivef Avatar answered Oct 12 '22 13:10

fivef


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
like image 18
Omnipresent Avatar answered Oct 12 '22 13:10

Omnipresent