Reputation: 3
I Have a Raspberry Pi with a Flask Server that uses OpenCV to stream my USB webcam to the flask Website.
One User can connect to the flask server and the video stream, but 2 User cant. The Problem is every time a user connects to the server, my camera.py script is starting and using the webcam. But when the webcam is already busy the camera.py script cant uses the webcam and the script crashes.
That means 2 Users are connected. 2 camera.py scripts are running and the only one can use the webcam.
Server.py
# main.py
from flask import Flask, render_template, Response
from camera import VideoCamera
app = Flask(__name__)
@app.route('/')
def index():
# rendering webpage
return render_template('test.html')
def gen(camera):
while True:
#get camera frame
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')
def getbytes(camera):
for x in range(10):
frame = camera.get_frame()
yield (frame)
@app.route('/getvideo')
def generate_video():
return Response(getbytes(VideoCamera()), mimetype="text/plain")
if __name__ == '__main__':
# defining server ip address and port
app.run(host='0.0.0.0',port='5000', debug=True)
Camera.py
#camera.py
# import the necessary packages
import cv2, urllib2, urllib
# defining face detector
face_cascade=cv2.CascadeClassifier("haarcascade_frontalface_alt2.xml")
ds_factor=0.6
class VideoCamera(object):
def __init__(self):
#capturing video
self.video = cv2.VideoCapture(0)
def __del__(self):
#releasing camera
self.video.release()
def get_frame(self):
#extracting frames
ret, frame = self.video.read()
frame = cv2.resize(frame,None,fx=ds_factor,fy=ds_factor,
interpolation = cv2.INTER_AREA)
gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
face_rects = face_cascade.detectMultiScale(gray,1.3,5)
for (x,y,w,h) in face_rects:
cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)
break
# encode OpenCV raw frame to jpg and displaying it
ret, jpeg = cv2.imencode('.jpg', frame)
return jpeg.tobytes()
Maybe someone can give me some tips or tutorials how I could change my code.
Upvotes: 0
Views: 1572
Reputation: 71
You can use function isOpened() to check if camera is open or not, and handle if is open, or you can open multiple cameras like this
ex:
cap0 = cv2.VideoCapture(0)
cap0.set(3,160)
cap0.set(4,120)
cap1 = cv2.VideoCapture(1)
cap1.set(3,160)
cap1.set(4,120)
Hope this is helpful.
Upvotes: 1