使用 Web(Html css) 和 Python 进行人脸检测

Tap*_*tro 6 html python opencv python-webbrowser flask-restful

我对网络技术很陌生。我正在制作一个集成了人脸检测的聊天机器人,尽管我知道如何使用 python 及其库与其他作品一起工作,但我在加载页面时遇到了问题

需求:web上的人脸检测,目前我们可以将其称为localhost。因此,为此,我准备了 OpenCV Harcascade 文件,并且检测部分也在发生。示例下面的图像和代码用于 web 和 pyton。

错误:通过单击 Weblink,python 烧瓶导航将进入挂起状态。

在此处输入图片说明

正如您在此处看到的那样,人脸检测正在运行,但是当我单击“收集我的图像”链接时,它会永远加载。请帮忙解决这个问题。

html代码:

<!DOCTYPE html>
<html>
<head>
    <title>Video Stream</title>
    <!-- <link rel="stylesheet" href="templates/css/main.css"> -->
</head>
<body>

<h2>ChatBot</h2>
<p >{{ alert }}</p>

<div class="container">
  <img class="bottomright" class="center" style="width: 500px;height: 300px;"src="{{ url_for('video_feed') }}">
  <div class="col-md-6 col-sm-6 col-xs-6"> <a href="/exec2" class="btn btn-sm animated-button victoria-one">Collect My Images</a> </div>
</div>  
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Python Main.py 类:-

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

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')

@app.route('/exec2')
def parse1():
#     response_data_collection = 
    print("Here")
    VideoCamera().save_to_dataset()
#     if response_data_collection != None:
#         print("Done with Collecting Data")
#     else:    
#         response_data_collection = "Couldn't able to create data files"
#     return render_template('index.html', alert='Done with Collecting Data')

@app.route('/training')
def training():
    return render_template('training.html', alert='Not Yet Trained')

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)
Run Code Online (Sandbox Code Playgroud)

需要帮助更正 parse1() 类。

VideoCamera.py:-(所有与人脸检测相关的py代码所在的位置)

import cv2
import os
import time
face_cascade=cv2.CascadeClassifier("haarcascade_frontalface_alt2.xml")
ds_factor=0.6
datasets = 'datasets'

class VideoCamera(object):
    def __init__(self):
        self.video = cv2.VideoCapture(0)

    def __del__(self):
        self.video.release()

    def get_frame(self):
        success, image = self.video.read()
        image=cv2.resize(image,None,fx=ds_factor,fy=ds_factor,interpolation=cv2.INTER_AREA)
        gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
        face_rects=face_cascade.detectMultiScale(gray,1.3,5)
        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()

    def save_to_dataset(self):
        return_data = ''
        sub_data = 'Tapan_1'
        (width, height) = (130, 100) 


        count = 1
        path = os.path.join(datasets, sub_data)
        if not os.path.isdir(path):
            os.mkdir(path)
            while count < 20: 
                success, image = self.video.read()
                image=cv2.resize(image,None,fx=ds_factor,fy=ds_factor,interpolation=cv2.INTER_AREA)
                gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
                face_rects=face_cascade.detectMultiScale(gray,1.3,5)
                for (x,y,w,h) in face_rects:
                    cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),2)
                    face = gray[y:y + h, x:x + w]
                    face_resize = cv2.resize(face, (width, height))
                    cv2.imwrite('%s/%s.png' % (path,count), face_resize)
                count += 1

                if count == 20:
                    return_data = '20 image captured.'
                    # cv2.waitKey(1)
                    # self.video.release()
                    # cv2.destroyAllWindow()
                    # time.sleep(1)

                    break
        else:
            return_data = "Data already Thr"

        return return_data
Run Code Online (Sandbox Code Playgroud)

因此,当我单击“收集我的图像”时,网络将进入挂起状态。

这是一些屏幕截图。

在此处输入图片说明

在此处输入图片说明

在这里你可以看到这里消息正在打印但没有导航到 exec2 页面,因此无法拍照。如果您认为捕获图像可能存在问题,我可以肯定地说这没有问题。我已经使用一个直接链接进行了测试,其中照片正在拍摄,因此 Videocamera python 代码没有问题。python 调用函数出了点问题。

如果您可以帮助我使用相同的代码,或者您有任何可以在这种情况下使用的参考代码,请告诉我谢谢。

Ali*_*ari 0

您的代码的问题似乎是您正在重新实例化VideoCamera导致代码尝试self.video = cv2.VideoCapture(0)两次。第二次VideoCamera实例化类时(即在函数中parse1),它尝试再次分配相同的相机(即编号 0),这是不可能的。您只能打开一次相机。

尝试实例化VideoCamera曾经的 Flask 应用程序,如下所示:

...

app = Flask(__name__)
app_wide_camera = VideoCamera()

...

@app.route('/video_feed')
def video_feed():
    # CHANGED HERE
    return Response(gen(app_wide_camera),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/exec2')
def parse1():
#     response_data_collection = 
    print("Here")
#   CHANGED HERE
    app_wide_camera.save_to_dataset()
...
Run Code Online (Sandbox Code Playgroud)