1

I have a Flask app with face detection script running and streaming it's output. If I load the app in a browser it works fine and showing video from pi. If reload the web page streaming fails and throwing an error:

picamera.exc.PiCameraAlreadyRecording: The camera is already using port 0

If I reload the apache2 server on which Flask app is running everything works fine. Here, is there is any way to stop previous camera instance/process?

I tried so many meothds using camera.stop_recording() and camera.close() but no luck.

facedetection.py:

#!/usr/bin/python3.5
from flask import Blueprint, render_template, Response
videoStreamBp = Blueprint('videoStream', __name__)

from picamera.array import PiRGBArray
from picamera import PiCamera
import time
from time import gmtime, strftime
import cv2

camera = PiCamera()
camera.resolution = (480, 320)
camera.framerate = 32
rawCapture = PiRGBArray(camera, size=(480, 320))
time.sleep(1)

face_cascade = cv2.CascadeClassifier('/var/www/haarcascade_frontalface_alt.xml')

def gen():
    for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
        image = frame.array
        gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(gray, 1.1, 5)
        print ("Found "+str(len(faces))+" face(s)")

        for (x,y,w,h) in faces:
            cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,0),2)
        #Save the result image
        img_name = "opencv_frame_{}.jpg".format(time)
        img = image.copy()
        (flag, encodedImage) = cv2.imencode(".jpg", img)
        yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + bytearray(encodedImage) + b'\r\n')
        rawCapture.truncate(0)

@videoStreamBp.route('/videoStream')
def getVideo():
    return Response(gen(),
                        mimetype='multipart/x-mixed-replace; boundary=frame')

/videoStream route is registered in index.py

Shyam3089
  • 459
  • 1
  • 5
  • 20

1 Answers1

0

You could check whether or not something is running already on your port with code like:

a_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
location = ("127.0.0.1", 0)
bool = a_socket.connect_ex(location)
if bool == 0:
    #Code for new camera