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

相关推荐
从孑开始3 小时前
ManySpeech.MoonshineAsr 使用指南
人工智能·ai·c#·.net·私有化部署·语音识别·onnx·asr·moonshine
涛涛讲AI3 小时前
一段音频多段字幕,让音频能够流畅自然对应字幕 AI生成视频,扣子生成剪映视频草稿
人工智能·音视频·语音识别
可触的未来,发芽的智生3 小时前
新奇特:黑猫警长的纳米世界,忆阻器与神经网络的智慧
javascript·人工智能·python·神经网络·架构
WWZZ20254 小时前
快速上手大模型:机器学习2(一元线性回归、代价函数、梯度下降法)
人工智能·算法·机器学习·计算机视觉·机器人·大模型·slam
AKAMAI4 小时前
数据孤岛破局之战 :跨业务分析的难题攻坚
运维·人工智能·云计算
Chicheng_MA4 小时前
算能 CV184 智能相机整体方案介绍
人工智能·数码相机·算能
Element_南笙4 小时前
吴恩达新课程:Agentic AI(笔记2)
数据库·人工智能·笔记·python·深度学习·ui·自然语言处理
倔强青铜三4 小时前
苦练Python第69天:subprocess模块从入门到上瘾,手把手教你驯服系统命令!
人工智能·python·面试
Antonio9154 小时前
【图像处理】rgb和srgb
图像处理·人工智能·数码相机
倔强青铜三4 小时前
苦练 Python 第 68 天:并发狂飙!concurrent 模块让你 CPU 原地起飞
人工智能·python·面试