Aakash Basu
Aakash Basu

Reputation: 1767

OpenCV's VideoCapture malfunctioning when fed from IP Camera

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?

Upvotes: 0

Views: 996

Answers (1)

Bedir Yilmaz
Bedir Yilmaz

Reputation: 4083

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

Upvotes: 1

Related Questions