0

So I'm running this piece of code.

import cv2
frameWidth = 640
frameHeight = 480
cap = cv2.VideoCapture("Resources/test_video.mp4")
while True:
    success, img = cap.read()
    if img is None:
        break
    img = cv2.resize(img, (frameWidth, frameHeight))
    cv2.imshow("Result", img)
    keyPressed = cv2.waitKey(5)
    if keyPressed == ord('q'):
        break;

test_video.mp4 is a short video here The moment it finishes running, the "Result" window freezes and become not responding. Even when I press "Q", nothing happens.

I run the program on Anaconda Spyder. cv2 is installed using pip install opencv-python

Edit: the code has been fixed so that the window exit when "q" is pressed

Huy Le
  • 1,439
  • 4
  • 19

1 Answers1

3

Try adding these two lines at the end:

import cv2
frameWidth = 640
frameHeight = 480
cap = cv2.VideoCapture("Resources/test_video.mp4")
    while True:
        success, img = cap.read()
        if img is None:
            break
        #img = cv2.resize(img, (frameWidth, frameHeight))
        cv2.imshow("Result", img)
        if cv2.waitKey(1) and 0xFF == ord('q'):
             break
cap.release()
cv2.destroyAllWindows()

It could be that it's failing to release the resource at the end of the script. See this post for further reference: What's the meaning of cv2.videoCapture.release()?

It also seems to be a common issue. See here and here.

Edit: Update to respond to comment requesting video exit on 'q'. Replace the lines:

if cv2.waitKey(1) and 0xFF == ord('q'):
    break

With:

key = cv2.waitKey(1)
if key == ord('q'):
    break

Tested and behaviour is as expected using:

  • Python 3.7
  • OpenCV 3.4.2
Robert Young
  • 456
  • 2
  • 8
  • This makes the program stop freezing, but I have another problem. When I press "Q", nothing happen while it should have break. Could you explain why ? – Huy Le Aug 06 '20 at 14:40
  • Have updated the answer with some code to allow video to exit on 'q' press. – Robert Young Aug 06 '20 at 15:02