|
|
import cv2 |
|
|
import os |
|
|
|
|
|
def rotate_video(input_path, output_path, rotation_angle=90): |
|
|
""" |
|
|
旋转视频文件 |
|
|
:param input_path: 输入视频路径 |
|
|
:param output_path: 输出视频路径 |
|
|
:param rotation_angle: 旋转角度 (90, 180, 270) |
|
|
:return: 是否成功 |
|
|
""" |
|
|
try: |
|
|
|
|
|
cap = cv2.VideoCapture(input_path) |
|
|
|
|
|
if not cap.isOpened(): |
|
|
print(f"无法打开视频文件: {input_path}") |
|
|
return False |
|
|
|
|
|
|
|
|
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) |
|
|
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) |
|
|
fps = cap.get(cv2.CAP_PROP_FPS) |
|
|
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) |
|
|
|
|
|
print(f"视频信息: {width}x{height}, FPS: {fps}, 总帧数: {total_frames}") |
|
|
|
|
|
|
|
|
if rotation_angle == 90 or rotation_angle == 270: |
|
|
output_width = height |
|
|
output_height = width |
|
|
else: |
|
|
output_width = width |
|
|
output_height = height |
|
|
|
|
|
|
|
|
fourcc = cv2.VideoWriter_fourcc(*'mp4v') |
|
|
out = cv2.VideoWriter(output_path, fourcc, fps, (output_width, output_height)) |
|
|
|
|
|
frame_count = 0 |
|
|
while True: |
|
|
ret, frame = cap.read() |
|
|
if not ret: |
|
|
break |
|
|
|
|
|
|
|
|
if rotation_angle == 90: |
|
|
rotated = cv2.rotate(frame, cv2.ROTATE_90_CLOCKWISE) |
|
|
elif rotation_angle == 180: |
|
|
rotated = cv2.rotate(frame, cv2.ROTATE_180) |
|
|
elif rotation_angle == 270: |
|
|
rotated = cv2.rotate(frame, cv2.ROTATE_90_COUNTERCLOCKWISE) |
|
|
else: |
|
|
print("不支持的旋转角度,请使用90, 180, 或270") |
|
|
return False |
|
|
|
|
|
|
|
|
out.write(rotated) |
|
|
frame_count += 1 |
|
|
|
|
|
if frame_count % 100 == 0: |
|
|
print(".1f") |
|
|
|
|
|
|
|
|
cap.release() |
|
|
out.release() |
|
|
|
|
|
print(f"视频旋转完成! 已处理 {frame_count} 帧") |
|
|
print(f"输出文件: {output_path}") |
|
|
return True |
|
|
|
|
|
except Exception as e: |
|
|
print(f"处理视频时出错: {str(e)}") |
|
|
return False |
|
|
|
|
|
if __name__ == "__main__": |
|
|
|
|
|
input_video = "videos/sample1_raw.mp4" |
|
|
output_video = "videos/sample1_rotated_270.mp4" |
|
|
|
|
|
|
|
|
if not os.path.exists(input_video): |
|
|
print(f"输入视频文件不存在: {input_video}") |
|
|
print("请确保视频文件在videos目录下") |
|
|
else: |
|
|
|
|
|
print("开始旋转视频...") |
|
|
success = rotate_video(input_video, output_video, 270) |
|
|
|
|
|
if success: |
|
|
print("视频旋转成功!") |
|
|
else: |
|
|
print("视频旋转失败!") |
|
|
|