본문 바로가기

PY(Python Image Processing)

python webapp test meidiapipe csv flask pillow opencv

728x90

[directory]

face_recognition_app/

├── app.py
├── known_faces/
│   ├── jiwon_han.jpg
│   └── jaewook_song.jpg
├── static/
│   └── styles.css
├── templates/
│   ├── index.html
│   └── result.html
└── requirements.txt

 

[app.py]

from flask import Flask, request, render_template, redirect
import cv2
import mediapipe as mp
import numpy as np
import os
import csv
from datetime import datetime

app = Flask(__name__)

# Fake database for demo purposes
user_data = {
    'Jiwon Han': '123-456-7890',
    'Jaewook Song': '098-765-4321'
}

# Initialize MediaPipe Face Detection
mp_face_detection = mp.solutions.face_detection
face_detection = mp_face_detection.FaceDetection(min_detection_confidence=0.2)
mp_drawing = mp.solutions.drawing_utils

# Load known face images and encodings
known_face_encodings = []
known_face_names = []

def load_known_faces():
    global known_face_encodings, known_face_names
    for name in user_data.keys():
        image_path = os.path.join('known_faces', f'{name.lower().replace(" ", "_")}.jpg')
        if os.path.exists(image_path):
            image = cv2.imread(image_path)
            if image is None:
                print(f"Error reading image file: {image_path}")
                continue
            rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            results = face_detection.process(rgb_image)
            if results.detections:
                for detection in results.detections:
                    bboxC = detection.location_data.relative_bounding_box
                    h, w, _ = image.shape
                    x, y, width, height = int(bboxC.xmin * w), int(bboxC.ymin * h), int(bboxC.width * w), int(bboxC.height * h)
                    face = image[y:y+height, x:x+width]
                    if face.size == 0:
                        print(f"Detected face has zero size: {image_path}")
                        continue
                    face_rgb = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
                    face_encoding = face_rgb.flatten()  # Flatten the face for demonstration
                    known_face_encodings.append(face_encoding)
                    known_face_names.append(name)

load_known_faces()

def save_to_csv(data):
    csv_file_path = 'uploads.csv'
    file_exists = os.path.isfile(csv_file_path)
    with open(csv_file_path, mode='a', newline='') as file:
        writer = csv.writer(file)
        if not file_exists:
            writer.writerow(['Timestamp', 'Image Filename', 'Name', 'Phone Number'])
        writer.writerow(data)

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

@app.route('/upload', methods=['POST'])
def upload():
    if 'file' not in request.files:
        return redirect(request.url)
    file = request.files['file']
    if file.filename == '':
        return redirect(request.url)
    if file:
        file_path = os.path.join('static', file.filename)
        file.save(file_path)

        # Load and process the uploaded image
        uploaded_image = cv2.imread(file_path)
        if uploaded_image is None:
            return f"Error reading uploaded image file: {file_path}"
        rgb_image = cv2.cvtColor(uploaded_image, cv2.COLOR_BGR2RGB)
        results = face_detection.process(rgb_image)

        name = 'Unknown'
        phone_number = 'Not found'

        # Check if the face matches any known faces
        if results.detections:
            for detection in results.detections:
                bboxC = detection.location_data.relative_bounding_box
                h, w, _ = uploaded_image.shape
                x, y, width, height = int(bboxC.xmin * w), int(bboxC.ymin * h), int(bboxC.width * w), int(bboxC.height * h)
                face = uploaded_image[y:y+height, x:x+width]
                if face.size == 0:
                    return "Detected face has zero size"
                face_rgb = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
                face_encoding = face_rgb.flatten()  # Flatten the face for demonstration
               
                # Compare encodings
                for known_encoding, known_name in zip(known_face_encodings, known_face_names):
                    if len(face_encoding) == len(known_encoding):
                        if np.allclose(face_encoding, known_encoding):
                            name = known_name
                            phone_number = user_data.get(name, 'Not found')
                            break

        # Save the result to a CSV file
        save_to_csv([datetime.now().strftime('%Y-%m-%d %H:%M:%S'), file.filename, name, phone_number])

        return render_template('result.html', name=name, phone_number=phone_number, image_url=file_path)

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

 

[styles.css]

body {
    font-family: Arial, sans-serif;
    margin: 20px;
    text-align: center;
}

h1 {
    color: #333;
}

img {
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 5px;
}

 

[index.html]

<!DOCTYPE html>
<html>
<head>
    <title>Face Matching Web App</title>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles.css') }}">
</head>
<body>
    <h1>Upload a Photo</h1>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file" accept="image/*">
        <input type="submit" value="Upload">
    </form>
</body>
</html>

 

[result.html]

<!DOCTYPE html>
<html>
<head>
    <title>Face Matching Result</title>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles.css') }}">
</head>
<body>
    <h1>Result</h1>
    <img src="{{ image_url }}" alt="Uploaded Image" style="width: 300px;">
    <p>Name: {{ name }}</p>
    <p>Phone Number: {{ phone_number }}</p>
    <a href="/">Upload another photo</a>
</body>
</html>

 

[operation]

pip install -r requirement.txt

python app.py

728x90