python把视频切成2秒_python利用ffmpeg将一段大视频等份的切成多个小视频段

在处理手机拍摄的视频时,由于存在rotate旋转参数,直接使用opencv裁剪可能会导致视频歪斜。通过结合ffmpeg,可以有效地解决这个问题。本文提供了一个Python函数cutVideo,该函数读取视频,获取其帧率和总帧数,然后利用ffmpeg按帧裁剪成多个2秒的小视频段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在剪辑视频的过程中发现部分手机拍摄的视频是带有rotate旋转矫正参数的,一般的opencv脚本剪辑出来的视频是歪的。查询了大量的资料找到一种使用ffmpeg剪辑的方法,将opencv和ffmpeg结合使用可以剪辑目前绝大多数的手机视频。

def cutVideo(path,filename):

video_full_path = path + r'\\' +filename

video_full_path_new = path + r'\\' +'new_'+filename

cap = cv2.VideoCapture(video_full_path)

cap.isOpened()

width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)

height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)

print(width, height)

if cap.isOpened(): # 当成功打开视频时cap.isOpened()返回True,否则返回False

# get方法参数按顺序对应下表(从0开始编号)

rate = cap.get(5) # 帧速率

FrameNumber = int(cap.get(7)) # 视频文件的帧数

duration = FrameNumber / rate # 帧速率/视频总帧数 是时间,除以60之后单位是分钟

len = int(duration)

fps = int(rate)

print(rate, FrameNumber)

if (width > height):

for i in range(0,len):

video_full_path_new = path + r'\\' + str(i) + filename

print(i)

cmd = 'ffmpeg -i {0} -vcodec copy -acodec copy -ss 00:00:0{1} -to 00:00:0{2} {3} -y'.format(video_full_path,str(i),str(i+1),video_full_path_new)

os.system(cmd)

else:

i = 0

while (True):

success, frame = cap.read()

if success:

i += 1

# print('i = ', i)

if (i % fps == 1):

videoWriter = cv2.VideoWriter(path + '/' + str(i) + filename,

cv2.VideoWriter_fourcc('D', 'I', 'V', 'X'), fps,

(int(width), int(height)))

videoWriter.write(frame)

else:

videoWriter.write(frame)

else:

print('end')

break

cap.release()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值