python - Python cv2 不写视频
问题描述
嗨,我正在尝试将长视频分解为较小的视频。我得到了一些互联网代码,但是当我运行它时,它不写视频我的代码有什么问题?我没有收到任何错误。
import cv2
count = 0
if __name__ == '__main__':
vidPath = 'VideoNietBewerkt.mp4'
shotsPath = '/videos/%d.avi' % count
segRange = [(0,1000),(1000,2000),(2000,3000)] # a list of starting/ending frame indices pairs
cap = cv2.VideoCapture(vidPath)
fps = int(cap.get(cv2.CAP_PROP_FPS))
size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
fourcc = int(cv2.VideoWriter_fourcc('X','V','I','D')) # XVID codecs
for idx,(begFidx,endFidx) in enumerate(segRange):
writer = cv2.VideoWriter(shotsPath,fourcc,fps,size)
cap.set(cv2.CAP_PROP_POS_FRAMES,begFidx)
ret = True # has frame returned
while(cap.isOpened() and ret and writer.isOpened()):
ret, frame = cap.read()
frame_number = cap.get(cv2.CAP_PROP_POS_FRAMES) - 1
if frame_number < endFidx:
writer.write(frame)
else:
break
writer.release()
count += 1
解决方案
编解码器(至少对我而言)和输出文件名似乎存在问题,该文件名未在循环外更新。
我为在我的机器上工作做了一些更改,用一部短片试试,代码本身几乎没有注释。
这对我有用:
import cv2
vidPath = 'movie.mp4'
segRange = [(0,30),(30,60),(60,90)] # <-- to fit my sample movie
cap = cv2.VideoCapture(vidPath)
fps = int(cap.get(cv2.CAP_PROP_FPS))
size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
fourcc = int(cv2.VideoWriter_fourcc(*'jpeg')) # <-- I had to change the codec
for idx,(begFidx,endFidx) in enumerate(segRange):
shotsPath = f'movie_{str(idx)}.avi' # <-- update filename here, use idx for naming the output file
print(f'saving file: {shotsPath}')
writer = cv2.VideoWriter() # <-- instantiate the writer this way
writer.open(shotsPath, fourcc, fps, size) # <-- open the writer
cap.set(cv2.CAP_PROP_POS_FRAMES, begFidx)
while(cap.isOpened() and writer.isOpened()): # removed and ret
ret, frame = cap.read()
frame_number = cap.get(cv2.CAP_PROP_POS_FRAMES) - 1
if frame_number < endFidx:
writer.write(frame)
else:
break
writer.release()
cap.release()
推荐阅读
- apache-flink - 如何针对 yarn-cluster 运行 sql-client
- apache-atlas - 无法在 Apache Atlas 中找到其他实体类型。只显示 hdfs_path
- php - Laravel 之间的日期时间
- c++ - 时间:2019-05-10 标签:c++lockfree queue implementationsingleproducersingleconsumer
- javascript - Datepicker 事件处理程序上的日期未更改
- python - 保存 Jupyter Notebook 时出现意外错误:'ascii' 编解码器无法在位置 1885 编码字符 u'\xd7':序数不在范围内(128)
- python - Tkinter 回调中的异常:IndexError:列表索引超出范围
- angular - Angular CLI 找不到所有 Bootstrap 类
- image - “docker”的未知命令“images”
- c# - Windows Form C# 应用程序在不同机器上运行时抛出无法加载文件或程序集“Mimekit”