Python and Opencv: I can't connect to camera ip Ezviz C6CN - python-3.x

I use Ezviz studio to change my ip address (When i connect to ezviz studio, i must to import verification code). I change Ip address of camera to 192.168.100.6. But i can't connect to my camera with python
import numpy as np
import cv2
cap = cv2.VideoCapture()
cap.open("http://192.168.100.6:8000/1")
while(True):
ret, frame = cap.read()
cv2.imshow('Stream IP camera opencv',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
error: OpenCV(4.1.0) 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'

Use
video_capture = cv2.VideoCapture('rtsp://admin:SZGBZT#192.168.1.2/h264_stream')
where admin is always admin and the password SZGBZT is the verification code on your camera

Related

OpenCV webcam reconnect

I'm using the OpenCV webcam example. Works great, but wondering, if it's possible to add a "camera reconnect function". When I unplug the camera, the code will crash. That's normal, but I would like to keep it running until I replug the camera again.
I tried "try: & except:" as you can see below. Now the python doesn't crash & when I unplug the camera, it will start printing "disconnected" to the console. However, when I reconnect the camera back, it would not start automatically, need to reset the program.
Thanks
import numpy as np
import cv2
cap = cv2.VideoCapture(2)
#cap = cv2.VideoCapture(1)
if cap.isOpened():
while(True):
try:
# Capture frame-by-frame
ret, im= cap.read()
# Display the resulting frame
cv2.imshow('frame', im)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
except:
print('Disconnected')
else:
print("camera open failed")
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

raspberry pi4 opencv and usb web camera python3 I had install opencv

in face recognition I write below code but I still have problem that USB webcam could not open in new window I try to put -1 and 1 and it dose not work
import cv2
cam = cv2.VideoCapture(0)
cv2.namedWindow("press space to take a photo", cv2.WINDOW_NORMAL)
cv2.resizeWindow("press space to take a photo", 500, 300)
img_counter = 0
while True:
ret, frame = cam.read()
if not ret:
print("failed to grab frame")
break
cv2.imshow("press space to take a photo", frame)
error message
[ WARN:0] global /tmp/pip-wheel-qd18ncao/opencv-python/opencv/modules/videoio/src/cap_v4l.cpp (893) open VIDEOIO(V4L2:/dev/video0): cant open camera by index
failed to grab frame

Python3 OpenCV - LIBTDB ERROR: data is not tagged properly

I'm getting this error by running this python script (converted into .exe) I found on github on my Acer Tablet with Windows 8.1:
LIBTDB ERROR: data is not tagged properly
(the script continues after printing the error)
import cv2
import numpy as np
import socket
import struct
from io import BytesIO
IP = '192.168.1.8'
# Capture frame
cap = cv2.VideoCapture(0) ## here the error
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((IP, 8080))
while cap.isOpened():
_, frame = cap.read()
memfile = BytesIO()
np.save(memfile, frame)
memfile.seek(0)
data = memfile.read()
# Send form byte array: frame size + frame content
client_socket.sendall(struct.pack("L", len(data)) + data)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
It works fine on my windows 10 pc, but I wanted to try it on two different devices.

Unable to capture image every 5 seconds using OpenCV

I am trying to capture image in every 5 seconds using opencv through my laptop's built-in webcam. I am using time.sleep(5) for the required pause. In every run, the first image seems to be correctly saved but after that rest all the images are being saved as an unsupported format (when i am opening them). Also I am unable to break the loop by pressing 'q'.
Below is my code.
import numpy as np
import cv2
import time
cap = cv2.VideoCapture(0)
framerate = cap.get(5)
x=1
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
cap.release()
# Our operations on the frame come here
filename = 'C:/Users/shjohari/Desktop/Retail_AI/MySection/to_predict/image' + str(int(x)) + ".png"
x=x+1
cv2.imwrite(filename, frame)
time.sleep(5)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
Any help is appreciated.
Just a small change, solved my issue.
I included the below code inside the loop :P
cap = cv2.VideoCapture(0)
framerate = cap.get(5)

Access IP camera with OpenCV

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()
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()
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
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:12345#192.168.1.1: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
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)
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
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()

Resources