关闭Pi camera的上一个实例

2024-04-28 11:04:54 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

我用camera.stop_recording()camera.close()试了这么多meothds,但没有成功

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路由在index.py中注册


Tags: fromimageimport应用程序flaskimgtimecv2
1条回答
网友
1楼 · 发布于 2024-04-28 11:04:54

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

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

相关问题 更多 >