Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

I am creating web application for face recognition using python flask app. I am already create static dataset. I need the text box to enter the name of the person after that capture image and it will store in to the dataset.

camera.py

import cv2 import os import time from flask import Response from pathlib import Path import uuid from contextlib import contextmanager from typing import Callable

face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") ds_factor = 0.6 font = cv2.FONT_HERSHEY_SIMPLEX

datasets = "datasets"

class VideoCamera: def __new__(cls, args, *kwargs): if getattr(cls, '_instance', False): return cls._instance

    cls._instance = super().__new__(cls, *args, **kwargs)
    return cls._instance

def __init__(self):
    if not hasattr(self, 'video'):
        self.video = cv2.VideoCapture(0)

def get_frame(self) -> bytes:
    success, image = self.video.read()
    if not success:
        return b''

    output = image.copy()
    cv2.rectangle(image, (400, 300), (800, 600), (255, 255, 255), 2)
    cv2.addWeighted(image, 0.5, output, 1 - .5, 0, output)
    cv2.resize(output, None, fx=ds_factor, fy=ds_factor, interpolation=cv2.INTER_AREA)
    gray = cv2.cvtColor(output, cv2.COLOR_BGR2GRAY)
    roi = gray[300:600, 400:800]  # ymin,ymax, xmin,xmax !

    faces = face_cascade.detectMultiScale(
        roi, scaleFactor=1.1,
        minNeighbors=5,
        minSize=(200, 200),
        flags=cv2.CASCADE_SCALE_IMAGE)

    for (x, y, w, h) in faces:
        cv2.rectangle(output, (x + 400, y + 300), (x + 400 + w, y + 300 + h), (255, 0, 0), 3)
        cv2.putText(output, 'Number of Faces : ' + str(len(faces)), (40, 40), font, 1, (255, 0, 0), 2)
        break
    ret, jpeg = cv2.imencode('.jpg', output)
    return jpeg.tobytes()

def save_to_dataset(self) -> str:
    data_set_size: int = 20
    sub_folder = 'swetha'
    (width, height) = (130, 100)

    dst_dir = Path(__file__).parent / Path(f'{datasets}/{sub_folder}')
    dst_dir.mkdir(parents=True, exist_ok=True)
    num_of_files = len([_ for _ in dst_dir.glob('*.*')])

    if num_of_files >= data_set_size:
        return ""

    for _ in range(data_set_size - num_of_files):
        success, image = self.video.read()
        output = image.copy()
        cv2.rectangle(image, (400, 300), (800, 600), (255, 255, 255), 2)
        cv2.addWeighted(image, 0.5, output, 1 - .5, 0, output)
        cv2.resize(output, None, fx=ds_factor, fy=ds_factor, interpolation=cv2.INTER_AREA)
        gray = cv2.cvtColor(output, cv2.COLOR_BGR2GRAY)
        roi = gray[300:600, 400:800]  # ymin,ymax, xmin,xmax !

        faces = face_cascade.detectMultiScale(
            roi, scaleFactor=1.1,
            minNeighbors=5,
            minSize=(200, 200),
            flags=cv2.CASCADE_SCALE_IMAGE)

        for (x, y, w, h) in faces:
            cv2.rectangle(output, (x + 400, y + 300), (x + 400 + w, y + 300 + h), (255, 0, 0), 3)
            cv2.putText(output, 'Number of Faces : ' + str(len(faces)), (40, 40), font, 1, (255, 0, 0), 2)
            face = gray[y + 300:y + 300 + h, x + 400:x + 400 + w]
            face_resize = cv2.resize(face, (width, height))
            cv2.imwrite(f'{dst_dir / Path(str(uuid.uuid4()))}.png', face_resize)
    return f'{data_set_size} image captured.'

app.py

from flask import Flask, render_template, Response, request, jsonify from werkzeug.utils import secure_filename from camera import VideoCamera from facerecog import VideoCamera import numpy as np from os import path, getcwd import pathlib import json import time import cv2 import os

app = Flask(__name__)

@app.route('/') def index(): timeNow = time.asctime(time.localtime(time.time())) # temp, hum = getDHTdata()

templateData = {
    'time': timeNow,
    # 'temp': temp,
    # 'hum': hum
}
return render_template('index.html', **templateData)

@app.route('/camera') def cam(): timeNow = time.asctime(time.localtime(time.time())) templateData = { 'time': timeNow } return render_template('camera.html', **templateData)

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 = VideoCamera().save_to_dataset() response_data_collection = "Done with Collecting Data" if response_data_collection else "you are already exist" return render_template('camera.html', alert=response_data_collection)

@app.route('/facerecog') def clock(): timeNow = time.asctime(time.localtime(time.time())) templateData = { 'time': timeNow } return render_template('recognize.html', **templateData)

def gen(facerecog): while True: frame = facerecog.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')

@app.route('/feed') def feed(): return Response(gen(VideoCamera()), mimetype='multipart/x-mixed-replace; boundary=frame')

if __name__ == '__main__': app.run(host='0.0.0.0', debug=True)

index.html

Face Recognition System

Go To The Face Recognition!

camera.html

<html> <head> <title>Add Face</title> <link rel="stylesheet" href="../static/style.css"/> <style> body { background-color: white; text-align: center; color: black; } </style> </head> <body>

Keep your face inside the box

{{ time }}


RETURN


</body> </html>

I am creating web application for face recognition using python flask app. I am already create static dataset. I need the text box to enter the name of the person after that capture image and it will store in to the dataset.

camera.py

import cv2 import os import time from flask import Response from pathlib import Path import uuid from contextlib import contextmanager from typing import Callable

face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") ds_factor = 0.6 font = cv2.FONT_HERSHEY_SIMPLEX

datasets = "datasets"

class VideoCamera: def __new__(cls, args, *kwargs): if getattr(cls, '_instance', False): return cls._instance

    cls._instance = super().__new__(cls, *args, **kwargs)
    return cls._instance

def __init__(self):
    if not hasattr(self, 'video'):
        self.video = cv2.VideoCapture(0)

def get_frame(self) -> bytes:
    success, image = self.video.read()
    if not success:
        return b''

    output = image.copy()
    cv2.rectangle(image, (400, 300), (800, 600), (255, 255, 255), 2)
    cv2.addWeighted(image, 0.5, output, 1 - .5, 0, output)
    cv2.resize(output, None, fx=ds_factor, fy=ds_factor, interpolation=cv2.INTER_AREA)
    gray = cv2.cvtColor(output, cv2.COLOR_BGR2GRAY)
    roi = gray[300:600, 400:800]  # ymin,ymax, xmin,xmax !

    faces = face_cascade.detectMultiScale(
        roi, scaleFactor=1.1,
        minNeighbors=5,
        minSize=(200, 200),
        flags=cv2.CASCADE_SCALE_IMAGE)

    for (x, y, w, h) in faces:
        cv2.rectangle(output, (x + 400, y + 300), (x + 400 + w, y + 300 + h), (255, 0, 0), 3)
        cv2.putText(output, 'Number of Faces : ' + str(len(faces)), (40, 40), font, 1, (255, 0, 0), 2)
        break
    ret, jpeg = cv2.imencode('.jpg', output)
    return jpeg.tobytes()

def save_to_dataset(self) -> str:
    data_set_size: int = 20
    sub_folder = 'swetha'
    (width, height) = (130, 100)

    dst_dir = Path(__file__).parent / Path(f'{datasets}/{sub_folder}')
    dst_dir.mkdir(parents=True, exist_ok=True)
    num_of_files = len([_ for _ in dst_dir.glob('*.*')])

    if num_of_files >= data_set_size:
        return ""

    for _ in range(data_set_size - num_of_files):
        success, image = self.video.read()
        output = image.copy()
        cv2.rectangle(image, (400, 300), (800, 600), (255, 255, 255), 2)
        cv2.addWeighted(image, 0.5, output, 1 - .5, 0, output)
        cv2.resize(output, None, fx=ds_factor, fy=ds_factor, interpolation=cv2.INTER_AREA)
        gray = cv2.cvtColor(output, cv2.COLOR_BGR2GRAY)
        roi = gray[300:600, 400:800]  # ymin,ymax, xmin,xmax !

        faces = face_cascade.detectMultiScale(
            roi, scaleFactor=1.1,
            minNeighbors=5,
            minSize=(200, 200),
            flags=cv2.CASCADE_SCALE_IMAGE)

        for (x, y, w, h) in faces:
            cv2.rectangle(output, (x + 400, y + 300), (x + 400 + w, y + 300 + h), (255, 0, 0), 3)
            cv2.putText(output, 'Number of Faces : ' + str(len(faces)), (40, 40), font, 1, (255, 0, 0), 2)
            face = gray[y + 300:y + 300 + h, x + 400:x + 400 + w]
            face_resize = cv2.resize(face, (width, height))
            cv2.imwrite(f'{dst_dir / Path(str(uuid.uuid4()))}.png', face_resize)
    return f'{data_set_size} image captured.'

app.py

from flask import Flask, render_template, Response, request, jsonify from werkzeug.utils import secure_filename from camera import VideoCamera from facerecog import VideoCamera import numpy as np from os import path, getcwd import pathlib import json import time import cv2 import os

app = Flask(__name__)

@app.route('/') def index(): timeNow = time.asctime(time.localtime(time.time())) # temp, hum = getDHTdata()

templateData = {
    'time': timeNow,
    # 'temp': temp,
    # 'hum': hum
}
return render_template('index.html', **templateData)

@app.route('/camera') def cam(): timeNow = time.asctime(time.localtime(time.time())) templateData = { 'time': timeNow } return render_template('camera.html', **templateData)

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 = VideoCamera().save_to_dataset() response_data_collection = "Done with Collecting Data" if response_data_collection else "you are already exist" return render_template('camera.html', alert=response_data_collection)

@app.route('/facerecog') def clock(): timeNow = time.asctime(time.localtime(time.time())) templateData = { 'time': timeNow } return render_template('recognize.html', **templateData)

def gen(facerecog): while True: frame = facerecog.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')

@app.route('/feed') def feed(): return Response(gen(VideoCamera()), mimetype='multipart/x-mixed-replace; boundary=frame')

if __name__ == '__main__': app.run(host='0.0.0.0', debug=True)

index.html

Face Recognition System

Go To The Face Recognition!

camera.html

<html> <head> <title>Add Face</title> <link rel="stylesheet" href="../static/style.css"/> <style> body { background-color: white; text-align: center; color: black; } </style> </head> <body>

Keep your face inside the box

{{ time }}


RETURN


</body> </html>