Access IP Camera in Python OpenCV
Asked Answered
S

12

42

How do I access my IP Camera stream?

Code for displaying a standard webcam stream is

import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while(True):
    ret, frame = cap.read()
    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

How do I do the same exact thing but with the IP Camera?

My system:

  • Python 2.7.14
  • OpenCV 2.4.9
  • Teledyne Dalsa Genie Nano XL Camera

You can use video capture Object as

camera = cv2.VideoCapture("IP:PORT/video")
Salyer answered 23/4, 2018 at 10:21 Comment(4)
Possible duplicate of Access IP camera with OpenCVHutner
Does your IP camera have a username and password?Dichlorodiphenyltrichloroethane
Hi check out this blog for IP camera & OpenCv.. benhowell.github.io/guide/2015/03/09/…Lawanda
Im researching the same thing, can you let me know how it goes? Also would you know if there is a brand and method that is easiest? (stream mpeg/jpeg, etc....) Thanks!Lawanda
S
8

I answer my own question reporting what therefore seems to be the most comprehensive overall procedure to Access IP Camera in Python OpenCV.

Given an IP camera:

  • Find your camera IP address
  • Find the port where the IP address is accessed
  • Find the protocol (HTTP/RTSP etc.) specified by the camera provider

Then, if your camera is protected go ahead and find out:

  • your username
  • your password

Then use your data to run the following script:

"""Access IP Camera in Python OpenCV"""

import cv2

stream = cv2.VideoCapture('protocol://IP:port/1')

# Use the next line if your camera has a username and password
# stream = cv2.VideoCapture('protocol://username:password@IP:port/1')  

while True:

    r, f = stream.read()
    cv2.imshow('IP Camera stream',f)

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

cv2.destroyAllWindows()

NOTE: In my original question I specify to being working with Teledyne Dalsa Genie Nano XL Camera. Unfortunately for this kind of cameras this normal way of accessing the IP Camera video stream does not work and the Sapera SDK must be employed in order to grab frames from the device.

Salyer answered 13/12, 2018 at 21:13 Comment(1)
Which local port is opened when we specify port in VideoCapture? I have two stream links with same port number and when the second one opens I get port already in use error.Retrochoir
D
50

An IP camera can be accessed in opencv by providing the streaming URL of the camera in the constructor of cv2.VideoCapture.

Usually, RTSP or HTTP protocol is used by the camera to stream video. An example of IP camera streaming URL is as follows:

rtsp://192.168.1.64/1

It can be opened with OpenCV like this:

capture = cv2.VideoCapture('rtsp://192.168.1.64/1')

Most of the IP cameras have a username and password to access the video. In such case, the credentials have to be provided in the streaming URL as follows:

capture = cv2.VideoCapture('rtsp://username:[email protected]/1')
Dichlorodiphenyltrichloroethane answered 23/4, 2018 at 10:45 Comment(6)
@sqarizvi How do I find the URL for the camera? It is installed in my local network, directly connected to the router. Is there any way to scan the network from a Python code and find the URL?Tonyatonye
@Abhishek... You can find the IP address of the camera using some network scanning utility such as arp-scan on linux. Further details of the URL i.e. Protocol, Credentials and Channel should be found in the camera manual or the software/mobile app shipped with the camera.Dichlorodiphenyltrichloroethane
Thanks for the reply. I can find the URL of the camera easily by accessing my router. But since my internet works with dynamic IP and the IP/URL of the camera keeps changing in case there is a power cut or something like that. So I was wondering if there exists something in python that can scan the network and find the IP for the camera so that I can use the URL of the camera as a variable instead of hardcoding it.Tonyatonye
@Abhishek, I think you can try with static ip configuration. Then you can have fixed ip instead of dynamic ip allocation.Urn
Recommend RTSP or HTTP?Forester
@sgarizvi, can this protocol be productionized? Is there any packet loss using RTSP? I've used GStreamer with Kinesis Video, my background is not much into video streaming, so, wish to know if I do not want to go for cloud, how can I best use the open source for a stable video streaming solution into Python.Endodontist
U
16

This works with my IP camera:

import cv2

#print("Before URL")
cap = cv2.VideoCapture('rtsp://admin:[email protected]/H264?ch=1&subtype=0')
#print("After URL")

while True:

    #print('About to start the Read command')
    ret, frame = cap.read()
    #print('About to show frame of Video.')
    cv2.imshow("Capturing",frame)
    #print('Running..')

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

cap.release()
cv2.destroyAllWindows()

I found the Stream URL in the Camera's Setup screen: IP Camera Setup Screen

Note that I added the Username (admin) and Password (123456) of the camera and ended it with an @ symbol before the IP address in the URL (admin:123456@)

Unsubstantial answered 7/6, 2019 at 5:50 Comment(8)
Can you share what camera you are using?Bashemeth
Commercial 2 Megapixel security camera. Most use the same or similar firmware and settings. I buy from UNIX CCTV. unixcctv.com/product-category/ip-cameras-nvr/ip-camerasUnsubstantial
Thanks for sharing. Was curious as I am not able to do same on Vivotek cameras.Bashemeth
Pretty much any ONVIF compatible camera that I have tried works this way. If you find out how to make it work on your Vivotek cameras, please post it here in case I ever run into the same situation you have in the future. ThanksUnsubstantial
@PratikKhadloya Your Vivotek camera's may need formatting something like this: ('rtsp://192.168.1.216/H264?ch=1&subtype=0?user=admin&pwd=123456')Unsubstantial
@JohnHarris can this protocol be productionized? Is there any packet loss using RTSP? I've used GStreamer with Kinesis Video, my background is not much into video streaming, so, wish to know if I do not want to go for cloud, how can I best use the open source for a stable video streaming solution into Python.Endodontist
I do believe I have the same camera of yours. In my case the camera has a label with brand/model information, at first: brand: ipsec model: ipc20 w1038. At the end, it seems a generic camera whose comercial companies will label any brand name.Leatrice
For the CCTV company I work with, I have noticed that no matter the brand or where it was manufactured, there are about 3 standard firmware's that control them. Even a $400 8 Megapixel PTZ camera that I have (from a different manufacturer) uses the same firmware as the 2 Megapixel in the picture above.Unsubstantial
F
13

The easiest way to stream video via IP Camera !

I just edit your example. You must replace your IP and add /video on your link. And go ahead with your project

import cv2

cap = cv2.VideoCapture('http://192.168.18.37:8090/video')

while(True):
    ret, frame = cap.read()
    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        cv2.destroyAllWindows()
        break
Fradin answered 15/10, 2018 at 4:39 Comment(3)
Does the port 8090 remains same for all the IP camera. If not, from where we can get the port number.?Housekeeping
hi Adrew, the link i mentioned above is picked from IP CAMERA App. So if you are using Android phone. You can download this app from Google Store. Then you sroll down and find "Start Server". Press on it. You will see the same type of link above. Good luckFradin
I am using IP Webcam from google playstore to get the video from cam on mobile phone and this worked for meSaker
S
9

First find out your IP camera's streaming url, like whether it's RTSP/HTTP etc.

Code changes will be as follows:

cap = cv2.VideoCapture("ipcam_streaming_url")

For example:

cap = cv2.VideoCapture("http://192.168.18.37:8090/test.mjpeg")
Salverform answered 23/4, 2018 at 10:28 Comment(3)
I am having an issue, I have tow cameras one over RTSP and Other over HTTP, Both of them works good on Ubuntu. When i transfered the same code to Raspberry pi, HTTP camera wouldn't return any framesWaldgrave
@Waldgrave suggest you to post that as independent questionSalverform
I am not getting any solution on this i posted the question here. raspberrypi.stackexchange.com/questions/84708/…Waldgrave
O
8

To access an Ip Camera, first, I recommend you to install it like you are going to use for the standard application, without any code, using normal software.

After this, you have to know that for different cameras, we have different codes. There is a website where you can see what code you can use to access them:

https://www.ispyconnect.com/sources.aspx

But be careful, for my camera (Intelbras S3020) it does not work. The right way is to ask the company of your camera, and if they are a good company they will provide it.

When you know your code just add it like:

cap = cv2.VideoCapture("http://LOGIN:PASSWORD@IP/cgi-bin/mjpg/video.cgi?&subtype=1")

Instead LOGIN you will put your login, and instead PASSWORD you will put your password.

To find out camera's IP address there is many softwares that you can download and provide the Ip address to you. I use the software from Intelbras, but I also recommend EseeCloud because they work for almost all cameras that I've bought:

https://eseecloud.software.informer.com/1.2/

In this example, it shows the protocol http to access the Ip camera, but you can also use rstp, it depends on the camera, as I said.

If you have any further questions just let me know.

Omari answered 6/12, 2018 at 12:4 Comment(1)
This Code is working, Thank YouCryptozoic
S
8

I answer my own question reporting what therefore seems to be the most comprehensive overall procedure to Access IP Camera in Python OpenCV.

Given an IP camera:

  • Find your camera IP address
  • Find the port where the IP address is accessed
  • Find the protocol (HTTP/RTSP etc.) specified by the camera provider

Then, if your camera is protected go ahead and find out:

  • your username
  • your password

Then use your data to run the following script:

"""Access IP Camera in Python OpenCV"""

import cv2

stream = cv2.VideoCapture('protocol://IP:port/1')

# Use the next line if your camera has a username and password
# stream = cv2.VideoCapture('protocol://username:password@IP:port/1')  

while True:

    r, f = stream.read()
    cv2.imshow('IP Camera stream',f)

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

cv2.destroyAllWindows()

NOTE: In my original question I specify to being working with Teledyne Dalsa Genie Nano XL Camera. Unfortunately for this kind of cameras this normal way of accessing the IP Camera video stream does not work and the Sapera SDK must be employed in order to grab frames from the device.

Salyer answered 13/12, 2018 at 21:13 Comment(1)
Which local port is opened when we specify port in VideoCapture? I have two stream links with same port number and when the second one opens I get port already in use error.Retrochoir
U
5

You can access most IP cameras using the method below.

import cv2 

# insert the HTTP(S)/RSTP feed from the camera
url = "http://username:password@your_ip:your_port/tmpfs/auto.jpg"

# open the feed
cap = cv2.VideoCapture(url)

while True:
    # read next frame
     ret, frame = cap.read()
    
    # show frame to user
     cv2.imshow('frame', frame)
    
    # if user presses q quit program
     if cv2.waitKey(1) & 0xFF == ord("q"):
        break

# close the connection and close all windows
cap.release()
cv2.destroyAllWindows()
Urn answered 17/5, 2019 at 7:6 Comment(1)
This worked great for me using a remote Raspberry pi running mjpg-streamer as video source. THANKS !Oliviaolivie
P
3

For getting the IP Camera video link:

  1. Open the IP Camera with given IP and PORT in browser
  2. Right click the video and select "copy image address"
  3. Use that address to capture video
Precipitancy answered 4/7, 2018 at 5:28 Comment(1)
I recently faced this issue and eventually solved it by using the inspect element feature of Firefox. I guess, just looking at the image address would have been even simpler . So, this is a more efficient way of finding the exact uri of camera's stream.Wynnie
R
2

In pycharm I wrote the code for accessing the IP Camera like:

import cv2

cap=VideoCapture("rtsp://user_name:password@IP_address:port_number")

ret, frame=cap.read()

You will need to replace user_name, password, IP and port with suitable values

Reiner answered 20/12, 2018 at 10:11 Comment(1)
You are going to have some sadness if you don't handle the stream and break cases properly (like the above answers do)!Piperine
T
2
import cv2
from threading import Thread
  
class Webcam:
  
    def __init__(self):
        # using video stream from IP Webcam for Android
        url = "http://your_ip:8080/video"
        self.video_capture = cv2.VideoCapture(url)
        self.current_frame = self.video_capture.read()[1]
          
    # create thread for capturing images
    def start(self):
        Thread(target=self._update_frame, args=()).start()
  
    def _update_frame(self):
        while(True):
            try:
                self.current_frame = self.video_capture.read()[1]
            except:
                pass
                  
    # get the current frame
    def get_current_frame(self):
        return self.current_frame

and then

from webcam import Webcam
# get image from webcam
image = self.webcam.get_current_frame()
Tab answered 21/6, 2021 at 10:57 Comment(0)
C
0

Getting the correct URL for your camera seems to be the actual challenge! I'm putting my working URL here, it might help someone. The camera is EZVIZ C1C with exact model cs-c1c-d0-1d2wf. The working URL is

rtsp://admin:[email protected]/h264_stream

where SZGBZT is the verification code found at the bottom of the camera. admin is always admin regardless of any settings or users you have.

The final code will be

video_capture = cv2.VideoCapture('rtsp://admin:[email protected]/h264_stream')
Choosy answered 25/11, 2019 at 22:12 Comment(0)
F
0

As mentioned above by @Gustavo GeoDrones you can find your Cam URL using https://www.ispyconnect.com/sources.aspx.

Go to the website, click on the model of your camera and a "Cam Video URL Generator" will appear. Insert your IP, username, etc. and click on "generate".

Cam URL for my Canon VB-H45 is (of course with my specific username, password and IP):

http://username:password@IP/-wvhttp-01-/video.cgi

The final code:

cap = cv2.VideoCapture('http://username:password@IP/-wvhttp-01-/video.cgi')
Flatto answered 7/9, 2020 at 14:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.