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度时,调整摆动方向。

相关推荐
love530love6 小时前
Windows 11 下再次成功本地编译 Flash-Attention 2.8.3 并生成自定义 Wheel(RTX 3090 sm_86 专属版)
人工智能·windows·笔记·编译·flash_attn·flash-attn·flash-attention
模型启动机6 小时前
港大联合字节跳动提出JoVA:一种基于联合自注意力的视频-音频联合生成模型
人工智能·ai·大模型
无心水6 小时前
【神经风格迁移:全链路压测】29、AI服务压测实战:构建全链路压测体系与高并发JMeter脚本设计
人工智能·高并发·混沌工程·全链路压测·ai镜像开发·ai镜像·神经风格
怪我冷i7 小时前
Zed编辑器安装与使用Agent Servers(腾讯CodeBuddy、阿里百炼Qwen Code、DeepSeek Cli)
人工智能·编辑器·ai编程·ai写作·zed
AI_Auto7 小时前
智能制造-AI质检六大场景
人工智能·制造
特立独行的猫a7 小时前
AI工具推荐:Google 神秘武器 CodeWiki ---上古项目的终极克星
人工智能
nn在炼金8 小时前
大模型领域负载均衡技术
人工智能·算法·负载均衡
久菜盒子工作室8 小时前
【A股复盘】2025.12.30
人工智能·经验分享·金融
EMQX8 小时前
利用 EMQX 消息队列解决关键物联网消息传递挑战
人工智能·后端·物联网·mqtt·emqx
凌峰的博客8 小时前
基于深度学习的图像修复技术调研总结(下)
人工智能·深度学习