Commit 79e2f982 authored by Паршина Екатерина Сергеевна's avatar Паршина Екатерина Сергеевна
Browse files

Upload New File

parent 51717e6a
No related merge requests found
Showing with 78 additions and 0 deletions
+78 -0
import streamlit as st
import numpy as np
import faiss
import cv2
import os
import pandas as pd
from deepface import DeepFace
from natsort import natsorted
metadata_path = '/content/drive/MyDrive/hse_faces_miem/staff_photo.csv'
images_dir = '/content/drive/MyDrive/hse_faces_miem'
st.write("Загрузка метаданных...")
staff_metadata = pd.read_csv(metadata_path)
st.write("Метаданные загружены.")
def extract_face_embedding(image_path):
try:
image = cv2.imread(image_path)
if image is None:
raise Exception(f"Не удалось загрузить изображение: {image_path}")
face_embedding = DeepFace.represent(img_path=image_path, model_name='Facenet', enforce_detection=False)
return np.array(face_embedding)
except Exception as e:
st.error(f"Ошибка при обработке изображения {image_path}: {e}")
return None
st.write("Извлечение эмбеддингов из изображений...")
face_embeddings = []
person_names = []
for file_name in natsorted(os.listdir(images_dir)):
if file_name.lower().endswith('.jpeg'):
path_to_img = os.path.join(images_dir, file_name)
embedding = extract_face_embedding(path_to_img)
if embedding is not None:
face_embeddings.append(embedding)
person_names.append(file_name)
face_embeddings = [emb[0]['embedding'] for emb in face_embeddings if emb is not None]
face_embeddings = np.array(face_embeddings)
if len(face_embeddings) == 0:
st.error("Не удалось загрузить эмбеддинги из исходных данных.")
else:
embed_dim = face_embeddings.shape[1]
index = faiss.IndexFlatL2(embed_dim)
index.add(face_embeddings)
st.write("Эмбеддинги успешно загружены и индексированы.")
st.title('Приложение для распознавания лиц')
uploaded_file = st.file_uploader("Загрузите своё изображение", type=["jpg", "jpeg", "png"])
if uploaded_file is not None:
image_save_path = "uploaded_img.jpg"
with open(image_save_path, "wb") as f:
f.write(uploaded_file.getbuffer())
st.image(image_save_path, caption='Ваше изображение', use_column_width=True)
st.write("Извлечение эмбеддинга из загруженного изображения...")
query_emb = extract_face_embedding(image_save_path)
if query_emb is not None:
query_emb = query_emb[0]['embedding']
distances, indices = index.search(np.array([query_emb]), 1)
best_match_distance = distances[0][0]
best_match_name = person_names[indices[0][0]]
matched_person = staff_metadata.name[staff_metadata.filename.eq(best_match_name)].values[0]
st.write(f"Наиболее похожий человек: {matched_person}")
st.write(f"Расстояние: {best_match_distance:.4f}")
# Показываем изображение наиболее похожего человека
matched_image_path = os.path.join(images_dir, best_match_name)
st.image(matched_image_path, caption=f'Наиболее похожий человек: {matched_person}', use_column_width=True)
else:
st.error("Не удалось получить эмбеддинг для изображения, проверьте его корректность.")
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment