如何使用OpenCV旋转视频

Cer*_*rin 7 python opencv image-processing

如何使用OpenCV旋转视频流中的所有帧?我尝试使用类似问题中提供的代码,但它似乎不适用于返回cv.RetrieveFrame的Iplimage图像对象.

这是我目前的代码:

import cv, cv2
import numpy as np

def rotateImage(image, angle):
    if hasattr(image, 'shape'):
        image_center = tuple(np.array(image.shape)/2)
        shape = image.shape
    elif hasattr(image, 'width') and hasattr(image, 'height'):
        image_center = (image.width/2, image.height/2)
        shape = np.array((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)
    result = cv2.warpAffine(image, rot_mat, shape, flags=cv2.INTER_LINEAR)
    return result

cap = cv.CaptureFromCAM(cam_index)
#cap = cv.CaptureFromFile(path)
fps = 24
width = int(cv.GetCaptureProperty(cap, cv.CV_CAP_PROP_FRAME_WIDTH))
height = int(cv.GetCaptureProperty(cap, cv.CV_CAP_PROP_FRAME_HEIGHT))

fourcc = cv.CV_FOURCC('P','I','M','1') #is a MPEG-1 codec

writer = cv.CreateVideoWriter('out.avi', fourcc, fps, (width, height), 1)
max_i = 90
for i in xrange(max_i):
    print i,max_i
    cv.GrabFrame(cap)
    frame = cv.RetrieveFrame(cap)
    frame = rotateImage(frame, 180)
    cv.WriteFrame(writer, frame)
Run Code Online (Sandbox Code Playgroud)

但这只是给出了错误:

  File "test.py", line 43, in <module>
    frame = rotateImage(frame, 180)
  File "test_record_room.py", line 26, in rotateImage
    result = cv2.warpAffine(image, rot_mat, shape, flags=cv2.INTER_LINEAR)
TypeError: <unknown> is not a numpy array
Run Code Online (Sandbox Code Playgroud)

大概是因为warpAffine需要一个CvMat而不是Iplimage.根据C++ cheatsheet,两者之间的转换是微不足道的,但我找不到任何关于在Python中做等效的文档.如何在Python中将Iplimage转换为Mat?

fra*_*xel 11

如果您刚刚旋转180度后,可以Flip在两个轴上使用,

更换:

frame = rotateImage(frame, 180)
Run Code Online (Sandbox Code Playgroud)

有:

cv.Flip(frame, flipMode=-1)
Run Code Online (Sandbox Code Playgroud)

这是'到位',所以它很快,你将不再需要你的rotateImage功能:)

例:

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

这个: 在此输入图像描述 这就是:在此输入图像描述