File size: 3,905 Bytes
d9e004e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#!/usr/bin/env python3
"""
Data Scientist.: Dr. Eddy Giusepe Chirinos Isidro

Reconhecimento de face e sorriso
================================
Neste pequeno projeto usamos OpenCV para detectar a face 
de imagens estáticas e sorrisos da mesma. Devemos ser cientes
que os modelos da OpenCV não são muito bons não, mas eles nos
ajudará a entender a aplicação da área de Visão Computacional.   


Execução:

$ python app.py 
"""
from flask import Flask, render_template, request
import cv2
import os
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'static/images'
app.config['ALLOWED_EXTENSIONS'] = {'jpg', 'jpeg', 'png', 'gif'}
app.config['MAX_IMAGE_SIZE'] = (800, 800)  # Defina o tamanho máximo desejado
app.config['DISPLAY_SIZE'] = (400, 400)  # Defina o tamanho para exibição

# Função para verificar extensões de arquivo permitidas:
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']

# Função para redimensionar a imagem se ela for muito grande:
def resize_image(image):
    height, width = image.shape[:2]
    max_height, max_width = app.config['MAX_IMAGE_SIZE']

    # Redimensiona apenas se a imagem for maior do que o tamanho máximo permitido:
    if height > max_height or width > max_width:
        ratio = min(max_height / height, max_width / width)
        new_height = int(height * ratio)
        new_width = int(width * ratio)
        return cv2.resize(image, (new_width, new_height))
    else:
        return image

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

# Rota para o upload da imagem:
@app.route('/upload', methods=['POST'])
def upload():
    if 'file' not in request.files:
        return render_template('index.html', error='Nenhum arquivo enviado')

    file = request.files['file']

    if file.filename == '':
        return render_template('index.html', error='Nenhum arquivo selecionado')

    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        file.save(filepath)

        # Processamento da imagem com OpenCV (detecção facial e de sorriso):
        image = cv2.imread(filepath)
        
        # Redimensiona a imagem se for muito grande:
        image = resize_image(image)
        
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        # O modelos da OpenCV:
        face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
        smile_cascade = cv2.CascadeClassifier('haarcascade_smile.xml')

        # Detecção facial:
        faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)
        
        for (x, y, w, h) in faces:
            cv2.rectangle(image, (x, y), (x+w, y+h), (255, 0, 0), 2)
            roi_gray = gray[y:y+h, x:x+w]
            
            # Detecção de sorriso:
            smiles = smile_cascade.detectMultiScale(roi_gray, scaleFactor=1.8, minNeighbors=20)
            if len(smiles) > 0:
                # Apenas considere a primeira detecção de sorriso
                sx, sy, sw, sh = smiles[0]
                cv2.rectangle(image, (x+sx, y+sy), (x+sx+sw, y+sy+sh), (0, 255, 0), 2)
            # for (sx, sy, sw, sh) in smiles:
            #     cv2.rectangle(image, (x+sx, y+sy), (x+sx+sw, y+sy+sh), (0, 255, 0), 2)

        # Redimensiona a imagem para exibição na interface:
        display_image = cv2.resize(image, app.config['DISPLAY_SIZE'])
        
        cv2.imwrite(filepath, image)

        return render_template('index.html', filename=filename, display_image=display_image)

    else:
        return render_template('index.html', error='Extensão de arquivo não permitida')


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