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

相关推荐
哔哩哔哩技术2 小时前
RIVAL:面向机器翻译的迭代对抗强化学习
人工智能
大模型真好玩2 小时前
低代码Agent开发框架使用指南(六)—Coze 变量与长期记忆
人工智能·coze·mcp
金融Tech趋势派2 小时前
企业微信私有化服务商怎么选?从数据安全与定制化需求看适配方向
大数据·人工智能·金融·企业微信·零售
IT_陈寒2 小时前
Python开发者必看:这5个鲜为人知的Pandas技巧让你的数据处理效率提升50%
前端·人工智能·后端
YF云飞2 小时前
AI编程:氛围狂欢还是工程灾难?
人工智能
光锥智能2 小时前
具身智能3D数字人开放平台「星云」发布:魔珐科技让AI第一次拥有“身体”
人工智能·科技·3d
sendnews2 小时前
红松APP首秀北京老博会,“有温度的科技”赋能退休兴趣生活
人工智能·物联网
美团技术团队2 小时前
ICCV 2025 | 美团论文精选及多模态推理竞赛冠军方法分享
人工智能
wwlsm_zql2 小时前
百度文心大模型再攀高峰:飞桨赋能AI,深度学习实力见证
人工智能·百度·paddlepaddle
王者鳜錸3 小时前
基于Selenium和AI的图像处理
图像处理·人工智能·selenium