OpenCV——实现视频图像的来回摆动的效果

python 复制代码
# Swing

import cv2

def rotate_img(image,angle):
    # Reading the image

    # dividing height and width by 2 to get the center of the image
    height, width = image.shape[:2]
    # get the center coordinates of the image to create the 2D rotation matrix
    center = (width/2, height/2)

    # using cv2.getRotationMatrix2D() to get the rotation matrix
    rotate_matrix = cv2.getRotationMatrix2D(center=center, angle=angle, scale=1)

    # rotate the image using cv2.warpAffine
    rotated_image = cv2.warpAffine(src=image, M=rotate_matrix, dsize=(width, height))

    return rotated_image

# 视频路径和输出路径
input_video_path = r'D:\desk\20240713_test\ORI_VIDEOS\ir_rotate_20240713.mp4'
output_video_path = r'D:\desk\20240713_test\ORI_VIDEOS\Rotate\20240713_ori_ir_swing\ir_swing_1_20240713.mp4'

# 打开视频文件
cap = cv2.VideoCapture(input_video_path)

# 获取视频的帧率和帧大小
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS)

# 定义输出视频的编码和创建VideoWriter对象
fourcc = cv2.VideoWriter_fourcc(*'XVID')  # 定义编码器和文件格式,XVID是DivX兼容的MPEG-4编码器
out = cv2.VideoWriter(output_video_path, fourcc, fps, (frame_width, frame_height), True)

angle = 0
frame_count = 0
fuhao = 1

while cap.isOpened():

    frame_count +=1
    ret, frame = cap.read()
    if not ret:
        break
        
    if frame_count % 1 == 0:
        if abs(angle) == 30:
            fuhao = -1*fuhao
        angle = angle + fuhao * 1
        print(angle)


    frame = rotate_img(frame,angle = angle)
    # 写入处理后的帧到输出视频
    out.write(frame)

    # 按 'q' 退出
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放资源
cap.release()
out.release()
cv2.destroyAllWindows()

解释:if frame_count % 1 == 0:设置多少帧处理一次,fuhao的作用是调整摆动方向,当angle角度的绝对值为30度时,调整摆动方向。

相关推荐
北方的银狐-Zero13 分钟前
OntoL对标Palantir功能简介-视频版
人工智能·图论·本体论
中微极客14 分钟前
Agentic AI实战:从原理到代码实现(基于Gemini 1.5)
人工智能
中微极客15 分钟前
AI视频生成器技术选型与工程实践指南(2026)
人工智能·音视频
zzzzzz31016 分钟前
我用 AI Agent 重构了日常开发工作流,效果出乎意料
人工智能·git·github
workflower18 分钟前
供应链分销网络选址问题
人工智能·机器学习·设计模式·自然语言处理·机器人
GIS数据转换器29 分钟前
智慧灌区管理平台
大数据·服务器·网络·数据库·人工智能·生活
STLearner1 小时前
ICML 2026 | LLM×Graph论文总结[2]【Graph4LLM,Graph4Agent,智能体记忆(Memory)
大数据·人工智能·python·深度学习·学习·机器学习·数据挖掘
ACP广源盛139246256732 小时前
此芯 P1 AI BOX / AI NAS@ACP#IX8008、IX8024 应用场景与市场机会
大数据·人工智能·分布式·单片机·嵌入式硬件
凤山老林2 小时前
从美团全栈化看 AI 冲击:前端转全栈,是自救还是必然
前端·人工智能·状态模式
大龄码农有梦想2 小时前
企业如何利用 AI 大模型提升业务效率?企业 AI 应用应该从哪些场景切入
人工智能·ai agent·ai智能体·ai应用·ai工作流·ai赋能·智能体平台