In the code I have a list of tuples (start frame,end frame) and I want to take the whole list and create a new video file from it, the problem it takes only the last couple on the list
import cv2
vidPath = "wingate_18-11-18_3mp_25m_pm_4m(3).mp4"
shotsPath = "new.avi"
segRange = [(0,40),(50,100),(200,400)] # 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()
The new video was created from 200 to 400 , not including any frames before. thanks very much for the help
答案 0 :(得分:0)
这是因为您的writer
用文件名shotsPath=new.avi
中的最后一个200-400覆盖了1-40和50-100。在每个段中向新文件声明一个新的writer
。
[编辑]
import cv2
vidPath = "1.MOV"
shotsPath = "new.avi"
segRange = [(0,40),(50,100),(200,400)] # 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
#declare writer before the for loop
writer = cv2.VideoWriter(shotsPath, fourcc, fps, size)
for idx, (begFidx, endFidx) in enumerate(segRange):
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
print(frame_number)
if frame_number < endFidx:
writer.write(frame)
else:
break
writer.release()
#Check how many frame that new.avi has
cap2 = cv2.VideoCapture("new.avi")
print(cap2.get(cv2.CAP_PROP_FRAME_COUNT))
>> 290 frames
结果正确。