0

I'm simply trying to read IP Camera live stream through OpenCV's simple code, i.e as follows:

import numpy as np
import cv2

src = 'rtsp://id:[email protected]'

cap = cv2.VideoCapture(src)

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Display the resulting frame
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

The problem here is, sometime it works like a charm by showing the running live video, but sometime else it creates a lot of blank windows which keeps popping up until the job is killed. Like the below image: enter image description here

Why does it happen, also how can we avoid it?

1 Answer 1

1

Maybe you should cover the case that the video capture fails to establish a healthy stream.

Note that it is possible to not to receive a frame in some cases even though video capture opens. This can happen due to various reasons such as congested network traffic, insufficient computational resources, power saving mode of some IP cameras.

Therefore, I would suggest you to check in the frame size and make sure that your VideoCapture object is receiving the frame at right shape. (You can debug and see the size of a visible frame to learn the expected resolution of the camera.)

A change in your loop like following might help

min_expected_frame_size = [some integer]
while(cap.isOpened()):
    ret, frame = cap.read()
    
    width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
    height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
    
    if ret==True and ((width*height) >= min_expected_frame_size):    
        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break
Sign up to request clarification or add additional context in comments.

4 Comments

Issue still persists after adding your portion of the code. Any guess what may be the root cause? Meaning, sometimes it is working, sometimes it isn't and popping up multiple of those blank windows.
This problem, I've observed, is not replicable when feeding from web cam, only happens with live IP Cameras.
Can you check the frame size in a healthy stream? Maybe the camera opens, but some empty frames are being streamed so you might want to check that case as well before you show the image. See the updated answer.
How to formulate a healthy frame size?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.