How to access Wireless Camera from IP webcam via open cv ? - python

import cv2
import urllib
import numpy as np
stream=urllib.urlopen('http://192.168.1.5:8080/frame.mjpg')
bytes=''
while True:
bytes+=stream.read(1024)
a = bytes.find('\xff\xd8')
b = bytes.find('\xff\xd9')
if a!=-1 and b!=-1:
jpg = bytes[a:b+2]
bytes= bytes[b+2:]
i = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.CV_LOAD_IMAGE_COLOR)
cv2.imshow('i',i)
if cv2.waitKey(1) ==27:
exit(0)
The code is not throwing any error too,I have set No authentication in IPWebcam.
Its throwing error Connection Refused

try this:
import urllib
import cv2
import numpy as np
import time
# Replace the URL with your own IPwebcam shot.jpg IP:port
url='http://192.168.20.108:8080/shot.jpg'
while True:
# Use urllib to get the image from the IP camera
imgResp = urllib.urlopen(url)
# Numpy to convert into a array
imgNp = np.array(bytearray(imgResp.read()),dtype=np.uint8)
# Finally decode the array to OpenCV usable format ;)
img = cv2.imdecode(imgNp,-1)
# put the image on screen
cv2.imshow('IPWebcam',img)
#To give the processor some less stress
#time.sleep(0.1)
# Quit if q is pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break

Related

method DESCRIBE failed: 453 Not Enough Bandwidth - OpenCv python

I' m trying to open two rtsp streams using opencv python, when I open only one stream I don't get this error, but when I try to open two or more streams the error occurs. My server is a NVR.
import os
from imutils.video import VideoStream, FileVideoStream, FPS
import cv2
import numpy as np
data1= "20201229T171900z"
data2= "20201229T172200z"
rtsp1 = "rtsp://user:pass#192.168.0.4:554/streaming/tracks/101?"
rtsp1 = rtsp1 + "starttime="+data1+"&endtime="+data2
rtsp2 = "rtsp://user:pass#192.168.0.4:554/streaming/tracks/201?"
rtsp2 = rtsp2 + "starttime="+data1+"&endtime="+data2
vs1 = VideoStream(rtsp1).start()
vs2 = VideoStream(rtsp2).start()
while(True):
frame1 = vs1.read()
frame2 = vs2.read()
frame1 = cv2.resize(frame1, (400,400))
frame2 = cv2.resize(frame2, (400,400))
esquerda = np.concatenate((frame1, frame2), axis=0)
cv2.imshow('img', esquerda)
key = cv2.waitKey(1)
if key == ord("q"):
break
vs1.stop()
vs2.stop()

Load BytesIO image with opencv

I'm trying to load an image with OPENCV from an io.BytesIO() structure.
Originally, the code loads the image with PIL, like below:
image_stream = io.BytesIO()
image_stream.write(connection.read(image_len))
image_stream.seek(0)
image = Image.open(image_stream)
print('Image is %dx%d' % image.size)
I tried to open with OPENCV like that:
image_stream = io.BytesIO()
image_stream.write(connection.read(image_len))
image_stream.seek(0)
img = cv2.imread(image_stream,0)
cv2.imshow('image',img)
But it seems that imread doesn't deal with BytesIO(). I'm getting an error.
I'm using OPENCV 3.3 and Python 2.7. Please, could someone help me?
Henrique
Try this:
import numpy as np
import cv2 as cv
import io
image_stream = io.BytesIO()
image_stream.write(connection.read(image_len))
image_stream.seek(0)
file_bytes = np.asarray(bytearray(image_stream.read()), dtype=np.uint8)
img = cv.imdecode(file_bytes, cv.IMREAD_COLOR)
The answer delivered by arrybn, worked for me. It was only necessary to add a cv2.waitkey(1) after cv2.imshow. Here is the code:
Server Side:
import io
import socket
import struct
import cv2
import numpy as np
server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 8000))
server_socket.listen(0)
connection = server_socket.accept()[0].makefile('rb')
cv2.namedWindow("Image", cv2.WINDOW_NORMAL)
try:
while True:
image_len = struct.unpack('<L', connection.read(struct.calcsize('<L')))[0]
if not image_len:
break
image_stream = io.BytesIO()
image_stream.write(connection.read(image_len))
image_stream.seek(0)
file_bytes = np.asarray(bytearray(image_stream.read()), dtype=np.uint8)
img = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
cv2.imshow("Image", img)
cv2.waitKey(1)
finally:
connection.close()
server_socket.close()
Based on the example Capturing to a network stream

Could anyone explain how to save RGB image from kinect on Raspberry Pi using OpenCV?

I tried cv.SaveImage function to accomplish it, but I was getting some unexpected error saying that writer not found. Thanks in advance.
/* This is my sample code */
import freenect
import cv
import frame_convert
import time
import cv2
import numpy as np
cv.NamedWindow('Depth')
cv.NamedWindow('RGB')
keep_running = True
def display_depth(dev, data, timestamp):
global keep_running
cv.ShowImage('Depth', frame_convert.pretty_depth_cv(data))
#time.sleep(1)
if cv.WaitKey(10) == 27:
keep_running = False
def display_rgb(dev, data, timestamp):
global keep_running
cv.Image= frame_convert.video_cv(data)
img = cv.CreateImage(cv.GetSize(cv.Image), cv.IPL_DEPTH_16S, 3)
cv.ShowImage('RGB',cv.Image)
for x in range(1,5):
name= "img%d" %(x)
cv.SaveImage('name',cv.Image);
time.sleep(1)
if cv.WaitKey(10) == 27:
keep_running = False
def body(*args):
if not keep_running:
raise freenect.Kill
print('Streaming from Kinnect... Please wait...Press ESC in window to stop')
freenect.runloop(depth=display_depth,
video=display_rgb,
body=body)
Using cv2.imwrite its very easier. Here I have saved RGB and Depth data as images in .png format but you can change it to whatever you want.
Hope it Helps.
#import the necessary modules
import freenect
import cv2
import numpy as np
#function to get RGB image from kinect
def get_video():
array,_ = freenect.sync_get_video()
array = cv2.cvtColor(array,cv2.COLOR_RGB2BGR)
return array
#function to get depth image from kinect
def get_depth():
array,_ = freenect.sync_get_depth()
array = array.astype(np.uint8)
return array
if __name__ == "__main__":
i = 0
while 1:
#get a frame from RGB camera
frame = get_video()
#get a frame from depth sensor
depth = get_depth()
#display RGB image
cv2.imshow('RGB image',frame)
#display depth image
cv2.imshow('Depth image',depth)
k = cv2.waitKey(5) & 0xFF
if k == 27: # wait for ESC key to exit
cv2.destroyAllWindows()
elif k == ord('s'): # wait for 's' key to save and exit
cv2.imwrite('frame'+str(i)+'.png',frame)
cv2.imwrite('depth'+str(i)+'.png',depth)
i = i+1
cv2.destroyAllWindows()
Try to change cv.SaveImage('name',cv.Image); into cv.SaveImage('name.jpg',cv.Image); in the display_rgb method.

How can i find optical flow of a live video stream (Android IPWebcam) in OpenCV Python?

I have written a code which works fine for a recorded video or video from webcam of my laptop.. but i need it to work with video directly from my phone.. Now i have been able to get video from phone and show it through python. But i need frames of this video to apply OpticalFlow function on it. (calcOpticalFlowFarneback).. Here's my two codes. i'll be thankful for your help.
This is code for getting video from android phone's camera to python
import cv2
import urllib2
import numpy as np
import sys
host = "192.168.1.2:8080"
if len(sys.argv)>1:
host = sys.argv[1]
hoststr = 'http://' + host + '/video'
print 'Streaming ' + hoststr
stream=urllib2.urlopen(hoststr)
bytes=''
while True:
bytes+=stream.read(1024)
a = bytes.find('\xff\xd8')
b = bytes.find('\xff\xd9')
if a!=-1 and b!=-1:
jpg = bytes[a:b+2]
bytes= bytes[b+2:]
i = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.IMREAD_COLOR)
cv2.imshow(hoststr,i)
if cv2.waitKey(1) ==27:
exit(0)
And this one is relevant portion for motion flow, notice i need frames from video
vid=cv2.VideoCapture('vidaflv.flv')
ret, frame = vid.read()
imgrayp = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
while True:
ret, frame = vid.read()
if ret:
imgray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
flow = cv2.calcOpticalFlowFarneback(imgrayp,imgray,None,0.5,3,15,3,5,1.2,0)
cv2.imshow('Optical flow',draw_flow(frame,flow))
imgrayp=imgray
if cv2.waitKey(1)==ord('e'):
break
what i can't figure out is how to get a frame from live stream video code to put in my optical flow fuction..
Withourt being able to test this, I'd try something like:
import cv2
import urllib2
import numpy as np
import sys
host = "192.168.1.2:8080"
if len(sys.argv)>1:
host = sys.argv[1]
hoststr = 'http://' + host + '/video'
print 'Streaming ' + hoststr
stream=urllib2.urlopen(hoststr)
bytes=''
FirstTime=True
while True:
bytes+=stream.read(1024)
a = bytes.find('\xff\xd8')
b = bytes.find('\xff\xd9')
if a!=-1 and b!=-1:
jpg = bytes[a:b+2]
bytes= bytes[b+2:]
i = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.IMREAD_COLOR)
if FirstTime=True:
FirstTime=False
imgrayp = cv2.cvtColor(i,cv2.COLOR_BGR2GRAY)
imgray = cv2.cvtColor(i,cv2.COLOR_BGR2GRAY)
flow = cv2.calcOpticalFlowFarneback(imgrayp,imgray,None,0.5,3,15,3,5,1.2,0)
cv2.imshow('Optical flow',draw_flow(frame,flow))
if cv2.waitKey(1) ==27:
exit(0)

Opencv two camera source

I am working with opencv and have two video source. I am using the following code. The code works sometimes and sometimes it does not work. Is there a problem with my code. How can I make the amends...
import cv2
Channel0 = cv2.VideoCapture(0)
IsOpen0, Image0 = Channel0.read()
Channel1 = cv2.VideoCapture(1)
IsOpen1, Image1 = Channel1.read()
while IsOpen0 and IsOpen1:
IsOpen0, Image0 = Channel0.read()
IsOpen1, Image1 = Channel1.read()
cv2.imshow("Webcamera",Image0)
cv2.imshow("Panasonic",Image1)
cv2.waitKey(10)
PS It always works when I use only one video source.
I think I figured out my error. For some reason the following code works. It must have been problem with threading...
import thread
import time
import cv2
def Webcamera():
Channel0 = cv2.VideoCapture(0)
IsOpen0, Image0 = Channel0.read()
while IsOpen0:
IsOpen0, Image0 = Channel0.read()
cv2.imshow("Webcamera",Image0)
cv2.waitKey(10)
if not IsOpen0:
time.delay(0.5)
print "Error opening Web camera"
def Panasonic():
Channel1 = cv2.VideoCapture(1)
IsOpen1, Image1 = Channel1.read()
while IsOpen1:
IsOpen1, Image1 = Channel1.read()
cv2.imshow("Panasonic",Image1)
cv2.waitKey(10)
if not IsOpen1:
time.sleep(0.5)
print "Error opening Panasonic"
try:
thread.start_new_thread(Webcamera,())
thread.start_new_thread(Panasonic,())
except:
print "Error: unable to start thread"
while 1:
pass

Categories