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. [closed]

asked 2020-12-08 03:23:09 -0600

revathi gravatar image

updated 2020-12-08 05:13:24 -0600

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 ... (more)

edit retag flag offensive reopen merge delete

Closed for the following reason question is off-topic or not relevant by berak
close date 2020-12-08 04:00:27.645026

Comments

1

off topics

LBerger gravatar imageLBerger ( 2020-12-08 03:44:33 -0600 )edit

btw, you probably cannot use the VideoCapture on your webserver

berak gravatar imageberak ( 2020-12-08 04:01:06 -0600 )edit