Access IP camera with OpenCV
Asked Answered
S

6

9

Can't access the video stream. Can any one please help me to get the video stream. I have searched in google for the solution and post another question in stack overflow but unfortunately nothing can't solve the problem.

import cv2
cap = cv2.VideoCapture()
cap.open('http://192.168.4.133:80/videostream.cgi?user=admin&pwd=admin')
while(cap.isOpened()):
    ret, frame = cap.read()
    cv2.imshow('frame', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()
Scheer answered 7/8, 2017 at 5:40 Comment(2)
What happens instead?Manipular
Maybe this will help anyone finding this thread? How to use opencv to capture video and using threads so much higher frame rate and reduced delay #55828951Gratt
S
5

Use code below to access ipcam directly through opencv. Replace the url in VideoCapture with your particular camera rtsp url. The one given generally works for most cameras I've used.

import cv2

cap = cv2.VideoCapture("rtsp://[username]:[pass]@[ip address]/media/video1")

while True:
    ret, image = cap.read()
    cv2.imshow("Test", image)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cv2.destroyAllWindows()
Samekh answered 8/2, 2019 at 11:35 Comment(0)
P
3

You can use urllib to read frames from video stream.

import cv2
import urllib
import numpy as np

stream = urllib.urlopen('http://192.168.100.128:5000/video_feed')
bytes = ''
while True:
    bytes += stream.read(1024)
    a = bytes.find(b'\xff\xd8')
    b = bytes.find(b'\xff\xd9')
    if a != -1 and b != -1:
        jpg = bytes[a:b+2]
        bytes = bytes[b+2:]
        img = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.IMREAD_COLOR)
        cv2.imshow('Video', img)
        if cv2.waitKey(1) == 27:
            exit(0)

Check this out if you want to stream video from webcam of your pc. https://github.com/shehzi-khan/video-streaming

Prado answered 7/8, 2017 at 9:42 Comment(1)
urllib and urllib2 are not available on Python 3.xInterdenominational
C
3

You can use this code to get live video feeds in browser.

for accessing camera other than your laptop's webcam, you can use RTSP link like this

rtsp://admin:[email protected]:554/h264/ch1/main/av_stream"

where

   username:admin
   password:12345
   your camera ip address and port
   ch1 is first camera on that DVR

replace cv2.VideoCamera(0) with this link like this for your camera and it will work

camera.py

import cv2

class VideoCamera(object):
    def __init__(self):
        # Using OpenCV to capture from device 0. If you have trouble capturing
        # from a webcam, comment the line below out and use a video file
        # instead.
        self.video = cv2.VideoCapture(0)
        # If you decide to use video.mp4, you must have this file in the folder
        # as the main.py.
        # self.video = cv2.VideoCapture('video.mp4')

    def __del__(self):
        self.video.release()

    def get_frame(self):
        success, image = self.video.read()
        # We are using Motion JPEG, but OpenCV defaults to capture raw images,
        # so we must encode it into JPEG in order to correctly display the
        # video stream.
        ret, jpeg = cv2.imencode('.jpg', image)
        return jpeg.tobytes()

main.py

from flask import Flask, render_template, Response
from camera import VideoCamera

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

def gen(camera):
    while True:
        frame = camera.get_frame()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')

@app.route('/video_feed')
def video_feed():
    return Response(gen(VideoCamera()),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)

then you can follow this blog to increase your FPS of video stream

Cyton answered 10/12, 2018 at 7:4 Comment(0)
S
2

Thank You. May be, now urlopen is not under utllib. It is under urllib.request.urlopen.I use this code:

import cv2
from urllib.request import urlopen
import numpy as np

stream = urlopen('http://192.168.4.133:80/video_feed')
bytes = ''
while True:
    bytes += stream.read(1024)
    a = bytes.find(b'\xff\xd8')
    b = bytes.find(b'\xff\xd9')
    if a != -1 and b != -1:
        jpg = bytes[a:b+2]
        bytes = bytes[b+2:]
        img = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.IMREAD_COLOR)
        cv2.imshow('Video', img)
        if cv2.waitKey(1) == 27:
            exit(0)
Scheer answered 7/8, 2017 at 10:11 Comment(2)
This does not work on python 3 TypeError: Can't convert 'bytes' object to str implicitlyUptotheminute
urllib and urllib2 are not available on Python 3.xInterdenominational
F
2

You can Use RTSP instead of direct video feed.

Every IP Camera have RTSP to Stream Live Video.

So you can use RTSP Link instead of videofeed

Family answered 7/5, 2018 at 17:51 Comment(0)
U
2

If using python 3, you will probably need to use a bytearray instead of a string. (modifying the current top answer)

with urllib.request.urlopen('http://192.168.100.128:5000/video_feed') as stream:

    bytes = bytearray()

    while True:
        bytes += stream.read(1024)
        a = bytes.find(b'\xff\xd8')
        b = bytes.find(b'\xff\xd9')
        if a != -1 and b != -1:
            jpg = bytes[a:b+2]
            bytes = bytes[b+2:]
            img = cv2.imdecode(np.frombuffer(jpg, dtype=np.uint8), cv2.IMREAD_COLOR)
            cv2.imshow('Video', img)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break

cv2.destroyAllWindows()
Uncurl answered 11/7, 2019 at 5:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.