Canlı video kaydından yaş ve cinsiyet tahmini

Hacknology

Kıdemli Üye
25 Eki 2015
2,713
0
rm -rf /
return_age.py
Kod:
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' 
import matplotlib.pyplot as plt
import tensorflow as tf
from matplotlib.image import imread
import sys, shutil
import numpy as np
from tqdm import tqdm
from sklearn.model_selection import train_test_split
import warnings

warnings.filterwarnings("ignore")
class myCallback(tf.keras.callbacks.Callback):
	def on_epoch_end(self, epoch, logs={}):
		if(logs.get('loss') <= 9):
			self.model.stop_training=True

callbacks = myCallback()
#os.chdir('..')
main_path = os.getcwd()
data_path = main_path + '\\datasets\\face_age'
def get_data():
    
    ages = os.listdir(data_path)
    X = []
    Y = []
    for age in tqdm(ages):
        ageint = int(age)

        new_folder = data_path + "\\{0}".format(age)
        photos = os.listdir(new_folder)
        for photo in photos:
            img = imread("{0}/{1}".format(new_folder, photo))
        
            X.append(img)
            Y.append(ageint)
    X = np.array(X, dtype=np.float16)
    Y = np.array(Y)
    X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=42)
    return (X_train, X_test, y_train, y_test)





def nn_model():

    model = tf.keras.models.Sequential([
        tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(200,200,3)),
        tf.keras.layers.MaxPooling2D(2,2),
        tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
        tf.keras.layers.MaxPooling2D(2,2),
        tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
        tf.keras.layers.MaxPooling2D(2,2),
        tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
        tf.keras.layers.MaxPooling2D(2,2),
        tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
        tf.keras.layers.MaxPooling2D(2,2),
        tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
        tf.keras.layers.MaxPooling2D(2,2),
        tf.keras.layers.Flatten(),
        tf.keras.layers.Dense(256, activation='relu'),
        tf.keras.layers.Dropout(0.2),
        tf.keras.layers.Dense(512, activation='relu'),
        tf.keras.layers.Dropout(0.2),
        tf.keras.layers.Dense(256, activation='relu'),
        tf.keras.layers.Dropout(0.2),
        tf.keras.layers.Dense(1, activation='relu')
    ])

    model.compile(optimizer='adam', loss='mse', metrics=['mae'])

    return model

def train_model():
    (X_train, X_test, y_train, y_test) = get_data()
    model = nn_model()
    model.fit(X_train, y_train, validation_data=(X_test,y_test), epochs=900, callbacks=[callbacks])
    model.save_weights('my_weights')
    model.save('my_model')

def return_age(frame):
    #frame = imread(frame, 0)/255
    frame = tf.expand_dims(frame, 0)
    new_model = nn_model()
    
    new_model.load_weights(main_path + '\\my_weights')
    p = new_model.predict(frame)
    return (str(int(np.round(p)[0][0])-3) + " - " + str(int(np.round(p)[0][0])+3))

return_gender.py
Kod:
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' 

import tensorflow as tf
import numpy as np

import matplotlib.pyplot as plt
from matplotlib.image import imread
from tensorflow.keras.preprocessing.image import ImageDataGenerator

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Dropout, Flatten
 
import logging
tf.get_logger().setLevel(logging.ERROR)
os.chdir('..')

data_path = 'C:\\Users\\Casper\\Desktop\\faceanalysis\\datasets\\face_gender\\'
def create_data(data_path):

    train_gen = ImageDataGenerator(rescale=1/255, rotation_range=0.2, zoom_range=0.2, horizontal_flip=True)
    train_data = train_gen.flow_from_directory(data_path+'train', target_size=(261,195), batch_size=16, color_mode='rgb', class_mode='binary')
    test_gen = ImageDataGenerator(rescale=1/255)
    test_data = test_gen.flow_from_directory(data_path+'test', target_size=(261,195), batch_size=16, color_mode='rgb', class_mode='binary', shuffle=False)
    class_names = train_data.class_indices
    return (train_data, test_data, class_names)
def create_model():
    
    model = Sequential()
    model.add(Conv2D(32, (3,3), input_shape=(261,195,3), activation='relu'))
    model.add(MaxPooling2D(2,2))
    model.add(Conv2D(32, (3,3), activation='relu'))
    model.add(MaxPooling2D(2,2))
    model.add(Conv2D(32, (3,3), activation='relu'))
    model.add(MaxPooling2D(2,2))
    model.add(Conv2D(32, (3,3), activation='relu'))
    model.add(MaxPooling2D(2,2))
    model.add(Flatten())
    model.add(Dense(512, activation='relu'))
    model.add(Dense(1, activation='sigmoid'))

    model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

    return model


def train_model(data_path):
    train_data, test_data, _ = create_data(data_path)
    model = create_model()
    
    model.fit_generator(train_data, validation_data=test_data, epochs=50)

    model.save_weights('my_gender_weights')
    model.save('my_gender_model')
def return_gender(frame):
    model = create_model()
    model.load_weights('C:\\Users\\Casper\\Desktop\\faceanalysis\\my_gender_weights')
    
    frame = tf.expand_dims(frame,0)
    p = model.predict(frame)
    liste = []
    i,j,class_names = create_data(data_path)
    for x,y in class_names.items():
        liste.append(x)
    return(liste[int(np.round(p[0][0]))])

main.py
Kod:
import return_age, return_gender
import cv2, time
import numpy as np

face_classifier = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
capture = cv2.VideoCapture(0)
font = cv2.FONT_HERSHEY_SIMPLEX
while True:
    _, frame = capture.read()
    gframe = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_classifier.detectMultiScale(gframe, 1.3,5)
    for (x,y,w,h) in faces:
        fc = gframe[y:y+h, x:x+w]
        roi = cv2.resize(fc, (200,200))
        rgbroi = cv2.cvtColor(roi, cv2.COLOR_GRAY2RGB)
        p1 = return_age.return_age(rgbroi)
        rgbroi = cv2.resize(rgbroi, (261,195))
        p2 = return_gender.return_gender(rgbroi)
        text = str(p1) + " / " + str(p2)
        cv2.putText(frame, text, (x,y),font, 1, (255,0,0), 2)
        cv2.rectangle(frame, (x,y), (x+w,y+h), (255,0,0), 2)
        cv2.imshow('Video', frame)
        cv2.waitKey(1000)
 
Üst

Turkhackteam.org internet sitesi 5651 sayılı kanun’un 2. maddesinin 1. fıkrasının m) bendi ile aynı kanunun 5. maddesi kapsamında "Yer Sağlayıcı" konumundadır. İçerikler ön onay olmaksızın tamamen kullanıcılar tarafından oluşturulmaktadır. Turkhackteam.org; Yer sağlayıcı olarak, kullanıcılar tarafından oluşturulan içeriği ya da hukuka aykırı paylaşımı kontrol etmekle ya da araştırmakla yükümlü değildir. Türkhackteam saldırı timleri Türk sitelerine hiçbir zararlı faaliyette bulunmaz. Türkhackteam üyelerinin yaptığı bireysel hack faaliyetlerinden Türkhackteam sorumlu değildir. Sitelerinize Türkhackteam ismi kullanılarak hack faaliyetinde bulunulursa, site-sunucu erişim loglarından bu faaliyeti gerçekleştiren ip adresini tespit edip diğer kanıtlarla birlikte savcılığa suç duyurusunda bulununuz.