Video Streaming from IP Camera in Python Using OpenCV cv2.VideoCapture
Asked Answered
G

1

10

I am trying to get video stream in python from IP camera but i am getting an error. I am Using Pycharm IDE.

import cv2
scheme = '192.168.100.23'


host = scheme
cap = cv2.VideoCapture('http://admin:Ebmacs8485867@'+host+':81/web/admin.html')

while True:
    ret, frame = cap.read()

    # Place options to overlay on the video here.
    # I'll go over that later.

    cv2.imshow('Camera', frame)

    k = cv2.waitKey(0) & 0xFF
    if k == 27:  # esc key ends process
        cap.release()
        break
cv2.destroyAllWindows()
Error:
"E:\Digital Image Processing\python\ReadingAndDisplayingImages\venv\Scripts\python.exe" "E:/Digital Image Processing/python/ReadingAndDisplayingImages/ReadandDisplay.py"
Traceback (most recent call last):
  File "E:/Digital Image Processing/python/ReadingAndDisplayingImages/ReadandDisplay.py", line 14, in <module>
    cv2.imshow('Camera', frame)
cv2.error: OpenCV(4.0.1) C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:352: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'

warning: Error opening file (/build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp:901)
warning: http://admin:[email protected]:81/web/admin.html (/build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp:902)
Giza answered 24/4, 2019 at 10:56 Comment(10)
You try to check the frame is empty or not, probably the is empty.Juggins
you mean the cv2.imshow is not able to capture the frames ?Giza
Not imshow(), but cap.read().Juggins
That link is a webpage (html) you need the rtsp link... and this depends on the model of the camera. Also you should check if cap.isOpened() before the loop and if ret after the ret, frame = cap.read() lineVick
i have tried with rtsp too, it is also not workingGiza
can you post the rtsp link you are using? rtsp requires also another port (probably 554)Vick
if i open image in new tab by click on the video stream.. the code captures the image but not capturing the frames for video.Giza
192.168.100.23:81/web/admin.htmlGiza
that is NOT a rtsp link, in some cameras is something like rtsp://192.168.100.23:554/11 ... This link changes from model to model. You are passing a html web page to connect to. This is NOT a stream but a web page. Sometimes this webpage connects to the stream via javascript or flash or something else.Vick
i wrote the line cap.isOpened() before while loop with if statement ... and it prints not opened when i run the codeGiza
C
17

You're most likely getting that error due to an invalid stream link. Insert your stream link into VLC player to confirm it is working. Here's a IP camera video streaming widget using OpenCV and cv2.VideoCapture.read(). This implementation uses threading for obtaining frames in a different thread since read() is a blocking operation. By putting this operation into a separate that that just focuses on obtaining frames, it improves performance by I/O latency reduction. I used my own IP camera RTSP stream link. Change stream_link to your own IP camera link.

enter image description here

Depending on your IP camera, your RTSP stream link will vary, here's an example of mine:

rtsp://username:[email protected]:554/cam/realmonitor?channel=1&subtype=0
rtsp://username:[email protected]/axis-media/media.amp

Code

from threading import Thread
import cv2

class VideoStreamWidget(object):
    def __init__(self, src=0):
        # Create a VideoCapture object
        self.capture = cv2.VideoCapture(src)

        # Start the thread to read frames from the video stream
        self.thread = Thread(target=self.update, args=())
        self.thread.daemon = True
        self.thread.start()

    def update(self):
        # Read the next frame from the stream in a different thread
        while True:
            if self.capture.isOpened():
                (self.status, self.frame) = self.capture.read()

    def show_frame(self):
        # Display frames in main program
        if self.status:
            self.frame = self.maintain_aspect_ratio_resize(self.frame, width=600)
            cv2.imshow('IP Camera Video Streaming', self.frame)

        # Press Q on keyboard to stop recording
        key = cv2.waitKey(1)
        if key == ord('q'):
            self.capture.release()
            cv2.destroyAllWindows()
            exit(1)

    # Resizes a image and maintains aspect ratio
    def maintain_aspect_ratio_resize(self, image, width=None, height=None, inter=cv2.INTER_AREA):
        # Grab the image size and initialize dimensions
        dim = None
        (h, w) = image.shape[:2]

        # Return original image if no need to resize
        if width is None and height is None:
            return image

        # We are resizing height if width is none
        if width is None:
            # Calculate the ratio of the height and construct the dimensions
            r = height / float(h)
            dim = (int(w * r), height)
        # We are resizing width if height is none
        else:
            # Calculate the ratio of the 0idth and construct the dimensions
            r = width / float(w)
            dim = (width, int(h * r))

        # Return the resized image
        return cv2.resize(image, dim, interpolation=inter)

if __name__ == '__main__':
    stream_link = 'your stream link!'
    video_stream_widget = VideoStreamWidget(stream_link)
    while True:
        try:
            video_stream_widget.show_frame()
        except AttributeError:
            pass

Related camera/IP/RTSP, FPS, video, threading, and multiprocessing posts

  1. Python OpenCV streaming from camera - multithreading, timestamps

  2. Video Streaming from IP Camera in Python Using OpenCV cv2.VideoCapture

  3. How to capture multiple camera streams with OpenCV?

  4. OpenCV real time streaming video capture is slow. How to drop frames or get synced with real time?

  5. Storing RTSP stream as video file with OpenCV VideoWriter

  6. OpenCV video saving

  7. Python OpenCV multiprocessing cv2.VideoCapture mp4

Clothilde answered 24/4, 2019 at 21:12 Comment(5)
This is good stuff. Thanks. Care to comment on the self.thread.daemon = True? Thanks.Galley
@Galley if you dont set daemon to True, it will be a zombie process when your main program dies. We set daemon True so that when our parent process dies, this will also kill all child processes. See daemon process boyzzzzzzClothilde
I created a get_frame function that returned either self.frame or np.empty if the first frame wasn't set and that gives me a set of frames to display or process outside the class. I was amazed at how little delay there is through this compared to VLC Player where objects appear several seconds after they have left the camera.Scrawl
Does self.frame need locking so that capture operation and show operation do not collide?Quitclaim
@KenjiNoguchi I found this answer to your question.Telegonus

© 2022 - 2024 — McMap. All rights reserved.