def get_estimate_age(url): try: image = url_to_image(url) except urllib.error.HTTPError: return False except urllib.error.URLError: return False except: return False agender = PyAgender() faces = agender.detect_genders_ages(image) if len(faces) > 0: return round(faces[0]['age']) else: return 0
class Agender(): def __init__(self): self.agender = PyAgender() def detect(self, img_path): # img_path = '/Users/woffee/www/language_design/couples-posing-800x450.jpg' faces = self.agender.detect_genders_ages(cv2.imread(img_path)) return faces
def gender_detect(path): ''' gender_detect: takes in an image file, uses OpenCV and PyAgender to detected the gender of the individual in the live image Parameters ---------- file: file name + location where file is stored Returns ------- Prediction string (i.e. "male") ''' agender = PyAgender() face = agender.detect_genders_ages(cv2.imread(path)) gender = face[0]['gender'] if gender >= 0.5: return 'Female' else: return 'Male'
def __init__(self, cascadePath=None, odir=None): ''' Constructor for PixelCore ''' self.cascPath = os.path.join(os.getcwd(), 'models', 'haarcascades', 'haarcascade_frontalface_extended.xml') resnetwts = os.path.join(cascadePath, 'models', 'weights.18-4.06.hdf5') if cascadePath: self.cascPath = os.path.join(os.path.abspath(cascadePath), 'models', 'haarcascades', 'haarcascade_frontalface_alt.xml') print('Loading HAAR-Cascade file: %s' % (self.cascPath)) self.faceCascade = cv2.CascadeClassifier(self.cascPath) self.face_size = 32 self.agender = PyAgender()
pictures = [] for i in onder_70: print(i) path = find(i,x) print(path) if str(path) != "None": z = find2('*.jpg', path) #pictures = pictures + " " + '"' + str(z[0]) + '"' #print(z) pictures.append(str(z[0])) print(pictures) #facemorpher.morpher(pictures, plot=True) facemorpher.averager(pictures, plot=True) agender = PyAgender() # see available options in __init__() src faces = agender.detect_genders_ages(cv2.imread("/Users/ellen/Documents/Twente/Q2/Introduction to biometrics/Final/result.png")) print(faces) # In[3]: # Vergelijk de gemiddelde leeftijd met de detected leeftijd van de morph van deze leeftijd groep from pyagender import PyAgender import cv2 import matplotlib.pyplot as plt agender = PyAgender()
from pyagender import PyAgender import numpy as np import matplotlib.pyplot as plt import cv2 from urllib.request import urlopen from datetime import datetime print("Importation Complete!") def list_format(phrase): return phrase[1:-1].replace("'", "").replace(" ", "").split(',') df = pd.read_csv("with_source.csv", encoding='utf-8') agender = PyAgender() print("csv read, agender created") df['urls'] = df['urls'].apply(list_format) img_sample = df.iloc[2]['urls'][1] req = urlopen(img_sample) arr = np.asarray(bytearray(req.read()), dtype=np.uint8) img = cv2.imdecode(arr, -1) no_profile = img print("no profile announced") data = { 'name': [],
import face_recognition import pickle import sqlite3 import sys import os import cv2 from pyagender import PyAgender res = PyAgender().detect_genders_ages(cv2.imread(sys.argv[1])) print('Age: {}'.format(res[0]['age'])) print('Gender: {}'.format(res[0]['gender'])) filename = sys.argv[1] known_image = face_recognition.load_image_file(filename) known_encoding = face_recognition.face_encodings(known_image)[0] con = sqlite3.connect('comparator.db') cur = con.cursor() ## write faces # cur.execute('create table if not exists faces (id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar(50), face blob)') # name_in_db = os.path.splitext(os.path.basename(filename))[0] # sql = 'insert into faces (name, face) values (?, ?)' # cur.execute(sql, (name_in_db, pickle.dumps(known_encoding))) # con.commit() ## recognize faces cur.execute('select name, face from faces') face_encodings = cur.fetchall() for i in range (0, len(face_encodings)): fe = pickle.loads(face_encodings[i][1])
def __init__(self): self.agender = PyAgender()
import imutils import cv2 import numpy as np import sys from utils import dirfiles, num2fixstr, imread from pyagender import PyAgender import dlib predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat') # parameters for loading data and images expression_model_path = '_mini_XCEPTION.106-0.65.hdf5' expression_classifier = load_model(expression_model_path, compile=False) EXPRESSIONS = ["angry","disgust","scared", "happy", "sad", "surprised","neutral"] agender = PyAgender() dirpath = '../faces/' img_names = dirfiles(dirpath,'*.jpg') n = len(img_names) print(n) print(img_names) gender_age = np.zeros((n,2)) landmarks = np.zeros((n,136)) for i in range(n): img = img_names[i]
def age_estimation(foto): agender = PyAgender() faces = agender.detect_genders_ages(cv2.imread(foto)) age = faces[0]['age'] return round(age)
# define store path store_root_dir = r"D:\Datasets\Korean" store_image_dir = os.path.join(store_root_dir, dataset_name + postfix) if os.path.exists(store_image_dir) is False: os.makedirs(store_image_dir) if os.path.exists(os.path.join(root_data_dir, dataset_name + '_F')) is False: os.makedirs(os.path.join(root_data_dir, dataset_name + '_F')) if os.path.exists(os.path.join(root_data_dir, dataset_name + '_E')) is False: os.makedirs(os.path.join(root_data_dir, dataset_name + '_E')) for filename in tqdm(os.listdir(image_root_dir)): filepath = os.path.join(image_root_dir, filename) if os.path.isdir(filepath): continue width = -1 height = -1 with Image.open(filepath) as img: width, height = img.size agender = PyAgender() # see available options in __init__() src faces = agender.detect_genders_ages(cv2.imread(MY_IMAGE)) # print(width, ", ", height) # if width <= 128 or height <= 128: #F # shutil.move(filepath, os.path.join(os.path.join(root_data_dir, dataset_name + '_F'), filename)) # elif width <= 256 or height <= 256: #E # shutil.move(filepath, os.path.join(os.path.join(root_data_dir, dataset_name + '_E'), filename))
def img_clss(): new_file_id=uuid.uuid1() try: data_file = request.files['img'] file_name = data_file.name data_file.save(f'{os.getcwd()}/images/{data_file.filename}') data_file.close() img_file = os.listdir(f'{os.getcwd()}/images/') print('Image ',img_file[0]) agender = PyAgender() path = os.path.join(f'{os.getcwd()}/images/', img_file[0]) print('Path ', path) faces = agender.detect_genders_ages(cv2.imread(path)) print('Faces ',faces) if faces[0]['gender'] < 0.5: faces[0]['gender'] = 'male' else: faces[0]['gender'] = 'female' faces[0]['age'] = str(faces[0]['age'] ).split('.')[0] print(faces[0]) resp = make_response(faces[0]) resp.headers.set('Content-Type','multipart/form-data') print('Response ', resp) return resp except Exception as e: print(e) try: # Camera capture path1 = f'{os.getcwd()}/images/' image_string = str(request.form.get('file_string')) image_newstring = image_string.replace("data:image/jpeg;base64,", "") imgdata = base64.b64decode(image_newstring) filename = os.path.join(path1 , new_file_id.hex+'.jpg') with open(filename, 'wb') as f: f.write(imgdata) f.close() img_file = os.listdir(f'{os.getcwd()}/images/') print('Image ',img_file[0]) agender = PyAgender() path = os.path.join(f'{os.getcwd()}/images/', img_file[0]) print('Path ',path) faces = agender.detect_genders_ages(cv2.imread(path)) print('Faces ' ,faces) if faces[0]['gender'] < 0.5: faces[0]['gender'] = 'male' else: faces[0]['gender'] = 'female' faces[0]['age'] = str(faces[0]['age'] ).split('.')[0] print(faces[0]) resp = make_response(faces[0]) resp.headers.set('Content-Type','multipart/form-data') target_dir=f'{os.getcwd()}/images/' with os.scandir(target_dir) as entries: for entry in entries: time.sleep(1) if entry.is_file() or entry.is_symlink(): os.remove(entry) print('Response ', resp) return resp except Exception as e: print(e) print("Something went wrong with your image. Kindly try with different image") finally: target_dir=f'{os.getcwd()}/images/' with os.scandir(target_dir) as entries: for entry in entries: time.sleep(1) print(entry) if entry.is_file() or entry.is_symlink(): os.remove(entry) print("Image Deleted")
srcs.append(img) for i in srcs: if not is_absolute(i): # if img has relative URL, make it absolute by joining i = urljoin(url, i) if i[0:2] == "//": i = "http:" + i if is_valid(i): urls.append(i) return urls ## commence scraping agender = PyAgender() for i in get_all_images(url): response = urllib.request.Request(i, headers=headers) try: with urllib.request.urlopen(response) as url: with open('temp.jpg', 'wb') as f: f.write(url.read()) except: print("Error: image not read") pass try: faces = agender.detect_genders_ages(cv2.imread("temp.jpg")) except:
import random def GetPhoto(): url = 'https://www.thispersondoesnotexist.com/image' user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36' request = urllib.request.Request(url, headers={'User-Agent': user_agent}) response = urllib.request.urlopen(request) html = response.read() f = open('img.jpg', 'wb') f.write(html) f.close() GetPhoto() agender = PyAgender() faces = agender.detect_genders_ages(cv2.imread('img.jpg')) age = int(faces[0]['age']) print("age: ", age) print("date of birth: " + str(int(str(datetime.now())[:4]) - age) + '.' + str(random.randint(1, 12)) + '.' + str(random.randint(1, 31))) if faces[0]['gender'] < 0.5: print('gender: male') gender = 'male' elif faces[0]['gender'] > 0.5: print('gender: female') gender = 'female' else: print('gender: idk') if random.randint(0, 1): gender = 'male'
import cv2 import numpy as np import pyrebase from pyagender import PyAgender agender = PyAgender() capture = cv2.VideoCapture(0) config = { "apiKey": "AIzaSyDT8zvCg7Ax3h_IYtpwaawKe_80LmoN0aY", "authDomain": "craeye-fa4f0.firebaseapp.com", "databaseURL": "https://craeye-fa4f0.firebaseio.com", "storageBucket": "craeye-fa4f0.appspot.com" } firebase = pyrebase.initialize_app(config) fb_database = firebase.database() while (True): ret, frame = capture.read() faces = agender.detect_genders_ages(frame) age_values = [] gender_values = [] input_data = {} if faces: for int_index in range(0, len(faces)): for value in faces[int_index]:
def __init__(self): self._detector = MTCNN() self._fa = FaceAligner() self._image_utils = Image_Utils() self._agender = PyAgender() self._gap_db = Gap_Db()
class Age_Gender_Detect(): def __init__(self): self._detector = MTCNN() self._fa = FaceAligner() self._image_utils = Image_Utils() self._agender = PyAgender() self._gap_db = Gap_Db() def detect_face_age_gender(self, fn, debug_mode=False): print("\nprocessing file %s..." % fn) # check if faces already detected for the family family_image_name = os.path.basename(fn).split('.')[0] family_id = self._gap_db.get_family_id(family_image_name) if self._gap_db.is_face_done(family_id): print("Faces already detected for the family! Moving on...\n") return else: # if faces not detected for the family yet, remove previous faces for # the family os.system("rm -rf %s" % (os.path.join(FACE_IMG_DIR, '%s*' % family_image_name))) img_original = cv2.imread(fn) if img_original.shape[0] >= img_original.shape[1]: img = imutils.resize(img_original, height=2000) else: img = imutils.resize(img_original, width=2000) faces = self._detector.detect_faces(img) self._image_utils.squarify_box(faces) if debug_mode: self._image_utils.show_key_points(img, faces) face_patches = self._image_utils.show_face_patches(img, faces, show=False) # align faces faces_aligned = self._fa.align(faces, img) assert len(faces_aligned) == len(face_patches) # detect age and gender ages = [] genders = [] for face in face_patches: g, a = self._agender.gender_age(face) gender = ['female' if g > 0.5 else 'male'][0] age = int(a) ages.append(age) genders.append(gender) print("gender: %s, age: %i" % (gender, age)) # save faces face_images = [] face_no = 0 for face in faces_aligned: face_fn = family_image_name + '_' + str(face_no) + '.jpg' face_images.append(face_fn[:-4]) # remove 'extension' face_f_fn = os.path.join(FACE_IMG_DIR, face_fn) cv2.imwrite(face_f_fn, face) face_no += 1 ## update database for image, age, gender in zip(face_images, ages, genders): self._gap_db.update_faces(family_id, image, age, gender)
"#climatechangescam", "#globalwarmingalarmism", "#globalwarmingcult", "#climatechangefrenzy", "#globalwarmingfraud", "#globalwarmingscam", "#globalwarmingnonsense", "#globalwarmingbullshit", "#climatefraud", "#climatescam", "#climatecult", "#climatenonsense", "#climatebullshit", "#climatechangebullshit", "#climatechangenonsense", "#climatechangecult", "#climatehysteria" ] #raw_data = [json.loads(line) for line in open(path_raw_data, 'r')] #raw_data = [] _d = 0 _b = 0 r = [] agender = PyAgender() #with open(path_out_data, 'w') as fp: # json.dump(r, fp) #for i, tweet in enumerate(raw_data): tweets = [] with open(path_raw_data, 'r') as infile: with open(path_out_data, 'w') as outfile: for i, line in enumerate(infile): tweet_in = json.loads(line) if i % 1000 == 0: print(f"{i}/?") #if i >= 100: # break tweet = {}
# -*- coding: utf-8 -*- """Untitled0.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1yA-cb7JozrTN3GaMLwhWENbCnqeB2YC_ """ from fer import FER import cv2 img = cv2.imread("/content/pic22.jpg") detector = FER() detector.detect_emotions(img) emotion, score = detector.top_emotion(img) score emotion from pyagender import PyAgender agender = PyAgender() faces = agender.detect_genders_ages(cv2.imread("/content/pic22.jpg")) faces
age_before_morph[idx] = age_estimation(i) # print(age_after_morph) # print(face_distance_after_morph) # print(actual_age) stop = time.time() print("Time: ", stop-start) np.savez(save_name, age_after_morph=age_after_morph,age_before_morph=age_before_morph, actual_age=actual_age, face_dist_after = face_distance_after_morph, face_dist_before=face_distance_before_morph) # Plots_print() #return age_after_morph, face_distance_after_morph, actual_age, face_distance_before_morph, age_before_morph def read_npz_after_morph(file): x = np.load(file, mmap_mode='r') actual_age = x['actual_age'] # Array with actual ages age_after_morph = x['age_after_morph'] # Array with detected ages after morphing age_before_morph = x['age_before_morph'] # Array with detected ages before morphing face_dist_after = x['face_dist_after'] # Face distance after morphing face_dist_before = x['face_dist_before'] # Face distance before morphing return actual_age, age_after_morph, age_before_morph, face_dist_after, face_dist_before agender = PyAgender() path = "../SiblingsDB/SiblingsDB_preprocessed/" #after_morphing("/Users/ellen/Documents/GitHub/Age-Obfuscation-Morphing/averages/average20_30_N3(1).png", path) #after_morphing("/Users/ellen/Documents/GitHub/Age-Obfuscation-Morphing/averages/average30_40_N3(0).png", path) # after_morphing("/Users/ellen/Documents/GitHub/Age-Obfuscation-Morphing/averages/average40_50_N3(0).png", path) # after_morphing("/Users/ellen/Documents/GitHub/Age-Obfuscation-Morphing/averages/average50_60_N3(0).png", path) after_morphing("../averages/average60_70_handpickedN2.png", path, agender)
from pyagender import PyAgender import cv2 import math from sklearn import neighbors import os import os.path import pickle from PIL import Image, ImageDraw import face_recognition from face_recognition.face_recognition_cli import image_files_in_folder import pandas as pd import numpy as np import datetime agender = PyAgender() df = pd.DataFrame(columns= ['name','age', 'gender','time_in','time_out']) def predict( imgMe,path,knn_clf=None, model_path=None, distance_threshold=0.6): if knn_clf is None and model_path is None: raise Exception("Must supply knn classifier either thourgh knn_clf or model_path") # Load a trained KNN model (if one was passed in) if knn_clf is None: with open(model_path, 'rb') as f: knn_clf = pickle.load(f) # Load image file and find face locations X_img = imgMe X_face_locations = face_recognition.face_locations(X_img)
def detect(image): agenda = PyAgender() ans = agenda.detect_genders_ages(image) return ans
# -*- coding: utf-8 -*- """ Created on Tue Dec 1 11:36:51 2020 @author: murie """ #import os, fnmatch, facemorpher from pyagender import PyAgender import cv2 agender = PyAgender() # see available options in __init__() src faces = agender.detect_genders_ages( cv2.imread( "C:/Users/murie/Documents/school/master/1B/Introduction2Biometrics/project_git/datasets/test" )) image = agender.detect_genders_ages(cv2.imread("acaro.png"))