import cv2
import os
def rotate_and_flip_video(input_video, output_video, rotation_degree, clockwise_rotation, horizontal_flip, vertical_flip):
"""
旋转和翻转视频
参数:
input_video (str): 输入视频文件名
output_video (str): 输出视频文件名
rotation_degree (float): 旋转角度,正值表示逆时针旋转,负值表示顺时针旋转
clockwise_rotation (bool): 是否顺时针旋转
horizontal_flip (bool): 是否水平镜像翻转
vertical_flip (bool): 是否竖直镜像翻转
"""
# 检查输入视频文件是否存在
if not os.path.isfile(input_video):
print("错误: 输入视频文件不存在")
return
# 打开视频文件
cap = cv2.VideoCapture(input_video)
if not cap.isOpened():
print("错误: 无法打开视频")
return
# 获取视频的帧率、宽度和高度
fps = cap.get(cv2.CAP_PROP_FPS)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
# 设置输出视频的编解码器及参数 (H.264 codec, .mp4 format)
fourcc = cv2.VideoWriter_fourcc(*'H264')
out = cv2.VideoWriter(output_video, fourcc, fps, (width, height))
frame_count = 0 # Initialize frame count
while True:
ret, frame = cap.read()
if not ret:
break
# 旋转图像
if clockwise_rotation:
rotated_frame = cv2.rotate(frame, cv2.ROTATE_90_CLOCKWISE)
else:
rotated_frame = cv2.rotate(frame, cv2.ROTATE_90_COUNTERCLOCKWISE)
# 根据horizontal_flip和vertical_flip变量决定是否进行镜像翻转
if horizontal_flip:
rotated_frame = cv2.flip(rotated_frame, flipCode=1)
if vertical_flip:
rotated_frame = cv2.flip(rotated_frame, flipCode=0)
# 写入输出视频
out.write(rotated_frame)
# 按q键退出
if cv2.waitKey(30) & 0xFF == ord('q'):
break
frame_count += 1
progress = (frame_count / total_frames) * 100
print(f"处理进度: {progress:.2f}%")
# 释放资源
cap.release()
out.release()
cv2.destroyAllWindows()
print("视频处理完成.")
# 打开生成的视频并播放
os.system(f"start {output_video}")
if __name__ == "__main__":
# 选择要旋转的视频文件和旋转角度(可以是任意角度)
input_video = "input.mp4"
output_video = "output.mp4" # 使用mp4格式
horizontal_flip = False # 设置是否水平镜像翻转
vertical_flip = False # 设置是否竖直镜像翻转
clockwise_rotation = True # 设置是否顺时针旋转(True为顺时针,False为逆时针)
rotation_degree = 180 # 设置旋转角度,可以是任意角度,这里设置为0度
# 旋转并镜像翻转视频
rotate_and_flip_video(input_video, output_video, rotation_degree, clockwise_rotation, horizontal_flip, vertical_flip)