Python下获取视频的旋转角度信息

1. 描述

使用手机等电子产品录制的视频在电脑上播放的时候是正的,但是使用OpenCV库进行读取的时候却是另外的角度,这是因为OpenCV在读取视频数据的时候没有去考虑视频内部保存的TAG信息(其中包含旋转角度等),但是使用OpenCV库却无法获取视频的旋转角度信息。对此,可以使用python包scikit-video进行获取。

安装scikit-video
pip install scikit-video

2. 参考代码

import cv2
import skvideo.io

# 得到旋转角度之后,对视频帧旋转对应的负角度便可以得到正向的图像
def rotate_img_data(img_data, degree):
    h, w = img_data.shape[:2]
    (cx, cy) = (w / 2, h / 2)

    # 设置旋转矩阵
    M = cv2.getRotationMatrix2D((cx, cy), -degree, scale=1.0)
    cos = np.abs(M[0, 0])
    sin = np.abs(M[0, 1])

    # 计算图像旋转后的新边界
    nW = int((h * sin) + (w * cos))
    nH = int((h * cos) + (w * sin))

    # 调整旋转矩阵的移动距离(t_{x}, t_{y})
    M[0, 2] += (nW / 2) - cx
    M[1, 2] += (nH / 2) - cy

    img_rotated = cv2.warpAffine(img_data, M, (nW, nH))
    return img_rotated

if __name__ == "__main__":
	file_name = "test.MOV"
    # get video info(rotate)
    video_metadata = skvideo.io.ffprobe(file_name)
    #video_tag_info = video_metadata['video']['tag']
    rotate_degree_info = -1.0
    for tag_info in video_metadata['video']['tag']:
    	for key, val in tag_info.items():
			if val == "rotate":
				rotate_degree_info = float(tag_info["@value"])
            	print("Info: video rotate degree info:{}".format(rotate_degree_info))
            	break
            
    # read video sequence
    video_io = cv2.VideoCapture(file_name)
    all_frame_nums = video_io.get(cv2.CAP_PROP_FRAME_COUNT)
    read_status, video_frame = video_io.read()
    while read_status:
    	# rotate the image if needs
        if abs(-1.0 - rotate_degree_info) > 1.0:
        	video_frame = rotate_img_data(video_frame.copy(), rotate_degree_info)
        read_status, video_frame = video_io.read()

PS:其中旋转部分代码来自:正确使用OpenCV和Python旋转图像

猜你喜欢

转载自blog.csdn.net/m_buddy/article/details/111938447