Телеграм Бот с распознаванием лиц

Alexandr Sakhno

Новичок
Пользователь
Окт 13, 2020
2
0
1
Всем здравствуйте. Я в новичок в питоне, поэтому не особо ориентируюсь в коде. Написал на днях код, просто соединив код от камеры и код с face_recognition с ролика на ютубе. Работает это так: камера сохраняет снимок в папку, а потом по этой фотке уже идет распознание лица, в папке faces лежат картинки с лицами, которые он может распознавать. Но после выполнение кода идет вывод изображения с подписью чье это лицо( как на картинке). Я бы хотел отправлять ботом просто имя без картинки(тип так: Adam Sandler)( на сайт или просто ботом), но что то не могу разобраться как это сделать. Помогите пожалуйста. Скриншот и сам код прикреплены

ОС: Windows 10
Python 3.8
Библиотеки: face_recognition, Dlib, os, numpy, sleep, telepot
Код:
import face_recognition as fr
import os
import cv2
import face_recognition
import numpy as np
from time import sleep
import telepot

TOKEN = '1057979295:AAGT6Apoxplmj_Dwr0LOmp9Dt0Rw9HdA6fc'

cap = cv2.VideoCapture(0)

ret, frame = cap.read()

cv2.imwrite('test.jpg', frame)

cap.release()


def get_encoded_faces():
    """
    looks through the faces folder and encodes all
    the faces

    :return: dict of (name, image encoded)
    """
    encoded = {}

    for dirpath, dnames, fnames in os.walk("./faces"):
        for f in fnames:
            if f.endswith(".jpg") or f.endswith(".png"):
                face = fr.load_image_file("faces/" + f)
                encoding = fr.face_encodings(face)[0]
                encoded[f.split(".")[0]] = encoding

    return encoded


def unknown_image_encoded(img):
    """
    encode a face given the file name
    """
    face = fr.load_image_file("faces/" + img)
    encoding = fr.face_encodings(face)[0]

    return encoding


def classify_face(im):
    """
    will find all of the faces in a given image and label
    them if it knows what they are

    :param im: str of file path
    :return: list of face names
    """
    faces = get_encoded_faces()
    faces_encoded = list(faces.values())
    known_face_names = list(faces.keys())

    img = cv2.imread(im, 1)
    #img = cv2.resize(img, (0, 0), fx=0.5, fy=0.5)
    #img = img[:,:,::-1]

    face_locations = face_recognition.face_locations(img)
    unknown_face_encodings = face_recognition.face_encodings(img, face_locations)

    face_names = []
    for face_encoding in unknown_face_encodings:
        # See if the face is a match for the known face(s)
        matches = face_recognition.compare_faces(faces_encoded, face_encoding)
        name = "Unknown"

        # use the known face with the smallest distance to the new face
        face_distances = face_recognition.face_distance(faces_encoded, face_encoding)
        best_match_index = np.argmin(face_distances)
        if matches[best_match_index]:
            name = known_face_names[best_match_index]

        face_names.append(name)

        for (top, right, bottom, left), name in zip(face_locations, face_names):


            # Draw a label with a name below the face
            font = cv2.FONT_HERSHEY_DUPLEX
            cv2.putText(img, name, (left -20, bottom + 15), font, 1.0, (255, 255, 255), 2)


    # Display the resulting image
    while True:

        cv2.imshow('Video', img)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            return face_names


print(classify_face("test.jpg"))
 

Вложения

  • Снимок.jpg
    Снимок.jpg
    62,2 КБ · Просмотры: 3
Последнее редактирование:

regnor

Модератор
Команда форума
Модератор
Июл 7, 2020
2 590
460
83
оформите код в теги code так ничего не понятно
Как правильно составить вопрос и не получить бан?
 

Форум IT Специалистов