Skip to content
GitLab
Explore
Projects
Groups
Topics
Snippets
Projects
Groups
Topics
Snippets
/
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Menu
Паршина Екатерина Сергеевна
AIMM
Commits
79e2f982
Commit
79e2f982
authored
1 month ago
by
Паршина Екатерина Сергеевна
Browse files
Options
Download
Patches
Plain Diff
Upload New File
parent
51717e6a
master
No related merge requests found
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
HW 4/Task2/app.py
+78
-0
HW 4/Task2/app.py
with
78 additions
and
0 deletions
+78
-0
HW 4/Task2/app.py
0 → 100644
+
78
−
0
View file @
79e2f982
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
:
.
4
f
}
"
)
# Показываем изображение наиболее похожего человека
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
This diff is collapsed.
Click to expand it.
Write
Preview
Supports
Markdown
0%
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment
Menu
Explore
Projects
Groups
Topics
Snippets