theastrocat
theastrocat

Reputation: 11

OpenCV (Python) not updating frame when read() is called

I am trying to pull individual frames at specified times from an RTSP feed.

This works fine for video streaming:

vcap = cv2.VideoCapture(RTSP_URL)

while(1):
    ret, frame = vcap.read()
    cv2.imshow('VIDEO', frame)
    cv2.waitKey(1)

But if I want to take an image every second and save it by doing something like this:

vcap = cv2.VideoCapture(RTSP_URL)

for t in range(60):
    ret, frame = vcap.read()
    if ret:
        cv2.imwrite("{}.jpg".format(t), frame)
    time.sleep(1);

Every image will look exactly the same as the first image. In every instance ret == True.

(Also this was working fine for me a week ago and then ipython did something that required me to do a re-install)

Upvotes: 1

Views: 2669

Answers (2)

theastrocat
theastrocat

Reputation: 11

Alright, after endless messing with it over the last few days, 1 second is not fast enough for the feed for whatever reason.

This will work:

vcap = cv2.VideoCapture(RTSP_URL)

for t in range(60):
    ret, frame = vcap.read()
    if ret and t % 1000 == 0:
        cv2.imwrite("{}.jpg".format(t), frame)
    time.sleep(0.001)

Upvotes: 0

Quang Hoang
Quang Hoang

Reputation: 150805

cv2.waitKey(1000) wouldn't do anything if you didn't show image with cv2.imshow(). Try:

vcap = cv2.VideoCapture(RTSP_URL)

for t in range(60):
    ret, frame = vcap.read()
    cv2.imwrite('{}.jpg'.format(t), frame)

    # this will activate the waitKey funciton
    cv2.imshow('preview', frame)
    cv2.waitKey(1000)

On another note, iPython/jupyter doesn't play well with the cv2's imshow and the whole GUI functionality. If, for example, you can't break the loop by keypress

if (cv2.waitKey(1000) == 27 & 0xff): break;

Upvotes: 1

Related Questions