读取视频并进行处理后(感兴趣区域裁剪)进行保存,保存格式为.MP4格式

'''
用于裁剪视频部分区域并将各区域保存为.mp4格式的新视频
'''

import cv2 as cv
import sys
# 读取视频文件,注意根据自己视频文件位置进行更换
video = cv.VideoCapture('C:/Users/sjh/Desktop/2021_6_16_19_30_39.h264')
# 获取视频帧率,25fps
fps = video.get(cv.CAP_PROP_FPS)
print(fps)
fourcc = cv.VideoWriter_fourcc('m', 'p', '4', 'v')
# 获取视频帧的宽高尺寸
sz = (int(video.get(cv.CAP_PROP_FRAME_WIDTH)/2), int(video.get(cv.CAP_PROP_FRAME_HEIGHT)/2))
print(sz)
vout_1 = cv.VideoWriter()
vout_1.open('C:/Users/sjh/Desktop/left_top.mp4',fourcc,fps,sz,True)
vout_2 = cv.VideoWriter()
vout_2.open('C:/Users/sjh/Desktop/right_top.mp4',fourcc,fps,sz,True)
vout_3 = cv.VideoWriter()
vout_3.open('C:/Users/sjh/Desktop/left_bottom.mp4',fourcc,fps,sz,True)
vout_4 = cv.VideoWriter()
vout_4.open('C:/Users/sjh/Desktop/right_bottom.mp4',fourcc,fps,sz,True)
count = 0
# 循环读取视频每一帧
while True:
    ret, frame = video.read()
    if ret == 1:
        # img_h, img_w, img_ch = frame.shape
        # 注意图像帧的尺寸顺序,先高度,后宽度
        print(count)
        # print(frame.shape)
        left_top = frame[0:962, 0:1280]
        right_top = frame[0:962, 1280:2560]
        left_bottom = frame[962:1924, 0:1280]
        right_bottom = frame[962:1924, 1280:2560]
        # left_top = cv.resize(left_top, (962, 1280))
        # 显示4个截取后的图像区域
        # cv.imshow('left_top', left_top)
        # cv.imshow('right_top', right_top)
        # cv.imshow('left_bottom', left_bottom)
        # cv.imshow('right_bottom', right_bottom)

        # 图像帧保存为.mp4视频
        vout_1.write(left_top)
        vout_2.write(right_top)
        vout_3.write(left_bottom)
        vout_4.write(right_bottom)
        count += 1

        # 按照帧率进行延时
        # cv.waitKey(int(1000 / int(fps)))
    else:
        break
vout_1.release()
vout_2.release()
vout_3.release()
vout_4.release()
sys.exit()

类似代码可以借鉴进行修改用于自己需求

import cv2 as cv
import numpy

cap = cv.VideoCapture('./*****.mp4')
fourcc = cv.VideoWriter_fourcc(*'mp4v')

width = int(cap.get(3))
height = int(cap.get(4))

out = cv.VideoWriter('new.mp4',fourcc,60,(width,height))  
#fps=60,这里是视频的帧率,可以随意调整,大小只影响每张图片的播放速率
#(width,height)图片的大小,如果是用视频则是分辨率大小.这里的值需与写入的图片或视频保持一致

while cap.isOpened():
    ret,frame = cap.read()
    if not ret:
        print('can not receive frame')
        break
    #图片像素翻转,0是x轴翻转,1是y轴翻转,-1是x和y一起
    # frame = cv.flip(frame,-1)
    out.write(frame)
    cv.namedWindow('frame',cv.WINDOW_NORMAL)
    # cv.resizeWindow('frame',200,100)
    # cv.imshow('frame', frame)
    if cv.waitKey(1) == ord('q'):
        break
cap.release()
out.release()
cv.destroyAllWindows()


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sjh_sjh_sjh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值