How to rotate a video with OpenCV

If you are just after a 180 degree rotation, you can use Flip on both axes,

replace:

frame = rotateImage(frame, 180)

with:

cv.Flip(frame, flipMode=-1)

This is 'in place', so its quick, and you won't need your rotateImage function any more :)

Example:

import cv
orig = cv.LoadImage("rot.png")
cv.Flip(orig, flipMode=-1)
cv.ShowImage('180_rotation', orig)
cv.WaitKey(0)

this: enter image description here becomes, this:enter image description here


You don't need to use warpAffine(), take a look at transpose() and flip().

This post demonstrates how to rotate an image 90 degrees.


Through trial-and-error I eventually discovered the solution.

import cv, cv2
import numpy as np

def rotateImage(image, angle):
    image0 = image
    if hasattr(image, 'shape'):
        image_center = tuple(np.array(image.shape)/2)
        shape = tuple(image.shape)
    elif hasattr(image, 'width') and hasattr(image, 'height'):
        image_center = tuple(np.array((image.width/2, image.height/2)))
        shape = (image.width, image.height)
    else:
        raise Exception, 'Unable to acquire dimensions of image for type %s.' % (type(image),)
    rot_mat = cv2.getRotationMatrix2D(image_center, angle,1.0)
    image = np.asarray( image[:,:] )

    rotated_image = cv2.warpAffine(image, rot_mat, shape, flags=cv2.INTER_LINEAR)

    # Copy the rotated data back into the original image object.
    cv.SetData(image0, rotated_image.tostring())

    return image0