具有dlib的人脸识别提供名称错误:未定义名称“face_utils”

2024-04-20 08:26:09 发布

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

我正在尝试制作一个flask web服务器,用于流式传输通过dlib人脸识别运行的相机的视频,但它给了我一个名称错误,告诉我没有定义“face_utils”,如何修复此错误? 如果我运行dlib面部识别,它会工作,但在这里它会给出错误 如果我只是得到相机图像,它也可以工作,但它只是不想一起工作

#main.py

from flask import Flask, render_template, Response
from camera import VideoCamera

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

def gen(camera):
    while True:
        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')

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)
#camera.py
import cv2
import dlib

import imutils

class VideoCamera(object):
    def __init__(self):
        self.video = cv2.VideoCapture(0)
    
    def __del__(self):
        self.video.release()
    
    def get_frame(self):
        detector = dlib.get_frontal_face_detector()
        predictor = dlib.shape_predictor(r'shape_predictor_68_face_landmarks.dat')
        success, image = self.video.read()
        image = imutils.resize(image, width=150)
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        rects = detector(gray, 1)
        for (i, rect) in enumerate(rects):
            shape = predictor(gray, rect)
            shape = face_utils.shape_to_np(shape)
            (x, y, w, h) = face_utils.rect_to_bb(rect)
            cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
            cv2.putText(image, "Mate".format(i + 1), (x - 5, y - 5),
                cv2.FONT_HERSHEY_DUPLEX, 0.5, (0, 255, 0), 1)
            for (x, y) in shape:
                cv2.circle(image, (x, y), 1, (0, 0, 255), -1)
        for (x,y,w,h) in face_rects:
            cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),2)
            break
        ret, jpeg = cv2.imencode('.jpg', image)
        return jpeg.tobytes()
#index.html
<html>
  <head>
    <title>Mod1</title>
    <style>
    img {
    display: block;
    margin-left: auto;
    margin-right: auto;
    width: 35%
    }
    </style>
  </head>
  <body>
    <h1 align="center">Video Streaming Demonistration</h1>
    <img id="bg" class="center" src="{{ url_for('video_feed') }}">
  </body>
</html>

Tags: imageimportselfappfordefhtmlvideo