0

我有一个带有人脸检测脚本的 Flask 应用程序正在运行并流式传输它的输出。如果我在浏览器中加载应用程序,它可以正常工作并显示来自 pi 的视频。如果重新加载网页流失败并抛出错误:

picamera.exc.PiCameraAlreadyRecording:相机已经在使用端口 0

如果我重新加载运行 Flask 应用程序的 apache2 服务器,一切正常。在这里,有什么方法可以停止以前的相机实例/进程?

我尝试了很多方法camera.stop_recording()camera.close()但没有运气。

人脸检测.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路线注册在index.py

4

1 回答 1

0

您可以使用以下代码检查端口上是否已经在运行某些东西:

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
于 2020-04-03T17:52:55.993 回答