<jupyter_start><jupyter_text>Face Detection - Face Recognition - Tracker: DATABASE'DEN YÜZLERİN ÖZELLİKLERİNİ ÇIKAR VE KAYDET<jupyter_code>os.add_dll_directory(os.path.join(os.environ['CUDA_PATH'], 'bin'))
from imutils import paths
import face_recognition
import pickle
import cv2
import os
import time
import dlib
import numpy as np
import multiprocessing as mp
import tkinter as tk
imagePaths = list(paths.list_images('../../../helper/trainImages'));
knownEncodings = [];
knownNames = [];

for (i, imagePath) in enumerate(imagePaths):
    #Resim yollarından dosya isimleri çıkartılır. (Sondan -2 de var)
    name = imagePath.split(os.path.sep)[-2];
    
    #Dosyalar çekilir
    image = cv2.imread(imagePath);
    
    #Gerekli dönüşümler yapılır.
    #dlib(RGB) 
    #OpenCV(BGR)
    image = np.array(image)
    rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB);

    #Yüzleri tespit etmek için HOG modeli kullanılır.
    #boxes = face_recognition.face_locations(rgb, model="hog");

    boxes = face_recognition.face_locations(rgb, model="cnn");

    #Yüzün encode bilgisini hesaplıyoruz.
    
    encodings = face_recognition.face_encodings(face_image=rgb, known_face_locations=boxes, model="small", num_jitters=1);

    #Encodeları isimleriyle beraber tutmak için
    for encoding in encodings:
        knownEncodings.append(encoding);
        knownNames.append(name);
    #end       
#end

#Son Kaydet
data = {"encodings": knownEncodings, "names": knownNames};

#Pickle ile verileri kaydet
f = open("encodes/face_enc", "wb");
f.write(pickle.dumps(data)),
f.close();
knownEncodings[1].shap<jupyter_output><empty_output><jupyter_text>KAYDEDİLEN YÜZ ENCODELARINI YÜKLE VE KAMERADAN GÖRÜNTÜ ALIP YÜZ TANIMLA<jupyter_code>os.add_dll_directory(os.path.join(os.environ['CUDA_PATH'], 'bin'))
from imutils import paths
import face_recognition
import pickle
import cv2
import os
import time
import dlib
import numpy as np
import multiprocessing as mp
import tkinter as tk
def takip(resim, bbox):
    x,y,w,h = int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3])
    cv2.rectangle(resim, (x, y), (x+w, y+h), (0, 255, 255), 1)
    cv2.putText(resim,"Takip",(x,y),cv2.FONT_HERSHEY_SCRIPT_SIMPLEX, 0.5, (0,255,255),1);
#end

def onMouse(event,x,y,flags,param):
    global mouseX, mouseY
    if event == cv2.EVENT_LBUTTONDBLCLK:
       mouseX, mouseY = x, y
#end

def alanSec(left,right,bottom,top,mouseX,mouseY):
    if(mouseX<right and mouseX>left and mouseX>top and mouseY<bottom):
        return True;
    else:
        return False;
#end

def landMarks(landmark, fr):
    print(landmark)
    for j in landmark:
        for i in landmark[j]:
            x,y=i
            x*=2;
            y*=2;
            print(x,y)
            fr = cv2.circle(fr, (x,y), 5, (255, 0, 0), 1)
    return fr;
#end

def fancyDraw(img, x, y, w, h, l=30, t=5, rt= 1):
    x1, y1 = x + w, y + h

    # Top Left  x,y
    cv2.line(img, (x, y), (x + l, y), (255, 0, 255), t)
    cv2.line(img, (x, y), (x, y+l), (255, 0, 255), t)
    # Top Right  x1,y
    cv2.line(img, (x1, y), (x1 - l, y), (255, 0, 255), t)
    cv2.line(img, (x1, y), (x1, y+l), (255, 0, 255), t)
    # Bottom Left  x,y1
    cv2.line(img, (x, y1), (x + l, y1), (255, 0, 255), t)
    cv2.line(img, (x, y1), (x, y1 - l), (255, 0, 255), t)
    # Bottom Right  x1,y1
    cv2.line(img, (x1, y1), (x1 - l, y1), (255, 0, 255), t)
    cv2.line(img, (x1, y1), (x1, y1 - l), (255, 0, 255), t)
    return img
#end

data = pickle.loads(open('encodes/face_enc', "rb").read());
face_locations = [];
face_encodings = [];
face_names = [];
islemYap = True;
yuzSec = False;
mouseX, mouseY = -1, -1
pool = mp.Pool(processes=4)


#vc = cv2.VideoCapture(0);
vc = cv2.VideoCapture("https://abc:123@192.168.1.103:8080/video");
#vc = cv2.VideoCapture("https://root:root123@192.168.43.1:1024/video");

vc.set(cv2.CAP_PROP_FRAME_WIDTH, 1280);
vc.set(cv2.CAP_PROP_FRAME_HEIGHT, 720);
#vc.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'));
#vc.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('A', 'V', 'C', '1'));
vc.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('H', '2', '6', '5')); #Daha iyi sıkıştırma sağlıyor.
vc.set(cv2.CAP_PROP_FPS, 60);

tracker = cv2.TrackerCSRT_create(); # Discriminative Correlation Filter
cv2.setMouseCallback('Takip',onMouse)

while True:
    tic = time.time();
    frame = []
    success = False
    (success, frame) = vc.read();
    while True:
        try:
            if(success):
                break;
        except:
            print("Kamera Bekleniyor...")
        (success, frame) = vc.read();

    fView = frame.view()
    gray = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR);
    small_frame = cv2.resize(gray, (0, 0), fx=0.5, fy=0.5);
    
    #Yüz Konum Tespiti ("cnn" veya "hog")-------------------------------------------------------------------------------------------------------
    #"face_locations" Kullanılan Modeller: 
        # 1-) dlib_face_recognition_resnet_model_v1.dat,
        # 2-) mmod_human_face_detector.dat,
        # 3-) shape_predictor_5_face_landmarks.dat,
        # 4-) shape_predictor_68_face_landmarks.dat
    face_locations = face_recognition.face_locations(small_frame, number_of_times_to_upsample=1, model="cnn"); #tuple-> top,right,bottom,left
    face_landmarks = face_recognition.api.face_landmarks(small_frame, face_locations=face_locations, model='large'); 
    
    #128-dimension face encoding
    face_encodings = face_recognition.face_encodings(face_image=small_frame, known_face_locations=face_locations, model="large", num_jitters=5);
    
    face_names = [];
    for face_encoding in face_encodings:
        matches = face_recognition.compare_faces(data["encodings"], face_encoding, tolerance=0.50)
        name = "Bilinmeyen"

        if True in matches:
            first_match_index = matches.index(True)
            name = data["names"][first_match_index]

            #end
        #end
        face_names.append(name)
    #end
    
    #Yüz landmarklarını çizmeye yarar - Aynı frame üzerinde paralel process uygulanacak ----------------------------------------------------------
    parallel = False
    if parallel == True:
        arg = []
        if face_landmarks!=[]:
            for k in range(len(face_landmarks)):
                arg.append((np.array(face_landmarks[k]), fView));
            try:
                frames = pool.starmap(landMarks, arg )
                #frame=frames[0] 
            except exp:
                print(exp)           

    else:
        if face_landmarks!=[]:
            for k in range(len(face_landmarks)):
            #face_landmarks ı paralel yapmalıyız.
                for j in face_landmarks[k]:
                    for i in face_landmarks[k][j]:
                        x,y=i
                        x*=2;
                        y*=2;
                        frame = cv2.circle(frame, (x,y), 5, (255, 255, 0), 1)


    #Yüzü çerçeve içerisine al------------------------------------------------------------------------------
    for (top, right, bottom, left), name in zip(face_locations, face_names):
        top *= 2
        right *= 2
        bottom *= 2
        left *= 2

        yuzSec = alanSec(left, bottom , right, top, mouseX, mouseY);
        
        if yuzSec == True:
            success, bbox = tracker.update(frame);
            if(success):
                takip(frame, bbox);
            else:
                cv2.putText(frame,"Kayboldu!",(50, 50), cv2.FONT_HERSHEY_SCRIPT_SIMPLEX, 0.5, (0,0,255),1);
        #end

        cv2.rectangle(frame, (left, top), (right, bottom), (255, 0, 255), 2)

        #İsim etiketi oluştur
        #frame = fancyDraw(frame, x, y, w, h, l=30, t=5, rt= 1
        cv2.rectangle(frame, (left, bottom - 25), (right, bottom), (255, 255, 255), cv2.FILLED)
        font = cv2.FONT_HERSHEY_DUPLEX
        cv2.putText(frame, name, (left + 5, bottom - 5), font, 0.5, (0, 0, 0), 1)
    #end

    # Oluşan çerçeveyi ekrana yansıt
    cv2.imshow('Takip', frame)
    #cv2.imshow('Takip', frame[:,::-1,:])
    toc = time.time();
    print(toc-tic)
    # Çıkış için 'q'
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    #end

#end

#Kamerayı kapat
vc.release();
cv2.destroyAllWindows();

cv2.destroyAllWindows()
vc.release();<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.17051918189519544, 'fraction_numerical': 0.03642744765823551, 'mean_word_length': 2.59304347826087, 'pattern_counts': {'":': 2, '<': 11, '<?xml version=': 0, '>': 12, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '305134', 'license': 'MIT', 'n_tokens_mistral': 3365, 'n_tokens_neox': 3107, 'n_words': 672, 'path': 'Face/dlib_face/Track/face_tracker.ipynb', 'repo_name': 'blitzkrieg0000/FaceRecognitionProcessesBundle', 'size': '8263'}