Search code examples
pythonopencvvideo-capture

Playback loop option in OpenCV videos


I am trying to build a playback loop option for an OpenCV video. My program uses Python multiprocessing, and has a button send loopswitch calls through queue4 to enable or disable the loop option. My specific problem is that my video freezes on the last frame, and I would like to know if the line vidFile.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, 1) is a correct use of the cv2.VideoCapture.set() method, and should indeed take the video back to frame 1 and replay it (as I think it should).

EDIT

After revising my code, it now triggers a runtime C++ error, but no other precisions are given. According to this answer, it would seem that using cv2.VideoCapture.set() to jump between frame is buggy. Has anyone managed it anyway?

Thank you,

My code for the capture process (queueand queue2 are in and out queues):

def image_capture(queue, con, queue2, queue4):
    videopath = con.recv()
    vidFile = cv2.VideoCapture(videopath)
    fps = vidFile.get(cv2.cv.CV_CAP_PROP_FPS)
    waitframe = 1/fps
    con.send(waitframe)#sending waitkey duration through pipe to update_image()
    loopswitch = False #init for playing video in a loop 
    while True:
        if queue4.empty():
           pass
        else:
           queueval = queue4.get()
            if queueval=='loop':
               if loopswitch==False:
                  loopswitch = True
               elif loopswitch==True:
                  loopswitch = False
        try:
            flag, frame=vidFile.read()
            if flag==0:
               if loopswitch==False:
                  queue2.put(None)
                  break
               elif loopswitch==True:
                  vidFile.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, 1)
                  continue
            else:                
               queue2.put(frame)
               cv2.waitKey(waitframe)
        except:
            continue

Solution

  • I partially solved it by replacing vidFile.set (cv2.cv.CV_CAP_PROP_POS_FRAMES, 1) by vidFile.set(cv2.cv.CV_CAP_PROP_POS_AVI_RATIO, 0), although this works for .avi files only.