Search code examples
pythonopencvvideo-processing

Trying to change Video Frame by key input


I am trying to perform cropping operations on every frame, so I want that every frame in the loop stays on hold till a certain key is pressed. The loop part of the code is given as follows:

while (True):

    # display the image and wait for a keypress
    ret, frame = cap.read()
    if not ret:
        print ('Process completed')
        break

    clone = frame.copy()
    cv2.imshow('frame',frame)

    if len(refPt) == 2:
        roi = clone[refPt[0][1]:refPt[1][1], refPt[0][0]:refPt[1][0]]
        cv2.imshow("ROI", roi)
        cv2.imwrite('New folder\\'+str(fileNum)+'.png',roi)
        fileNum += 1
        refPt.clear()
        #cv2.waitKey(0)

    key = cv2.waitKey(1) & 0xFF

    # if the 'q' key is pressed, exit from loop
    if key == ord("q"):
        break

    #if the 'n' key is pressed, go to next frame
    if key == ord("n"):
        continue

When the video goes into loop, it doesn't stop and wait for the 'n' keypress to change, rather the frame passes on quickly till I click and drag some point which activates the selection of a region part.

I feel my while condition is not correct. Do help me with the while condition.


Solution

  • This command only waits for 1ms and then goes on.

    key = cv2.waitKey(1) & 0xFF 
    

    try changing it to

    key = cv2.waitKey(0) & 0xFF
    

    this should wait until a key is pressed, if a cv window is available.