Example #1
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
Example #2
0
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
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'
Example #4
0
def detect(image):
    agenda = PyAgender()
    ans = agenda.detect_genders_ages(image)
    return ans
def age_estimation(foto):
    agender = PyAgender()
    faces = agender.detect_genders_ages(cv2.imread(foto))
    age = faces[0]['age']
    return round(age)
Example #6
0
    # 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))
Example #7
0
                    "profile_image_url"].replace("_normal", "")
                filename, file_extension = os.path.splitext(
                    tweet_in["user"]["profile_image_url"])
                _my_img_path = path_img_data + tweet_in["user"][
                    "id_str"] + file_extension

                if file_extension in ["", ".gif"]:
                    # The face predict tool doesn't work with some type of imgs.
                    face_predict = []
                else:
                    # Predict age and gender
                    try:
                        urllib.request.urlretrieve(
                            tweet_in["user"]["profile_image_url"],
                            _my_img_path)
                        face_predict = agender.detect_genders_ages(
                            cv2.imread(_my_img_path))
                    except:
                        face_predict = []
                        #print(f"EXCEPT: {_my_img_path}    {tweet_in['user']['profile_image_url']}")
                for f in face_predict:
                    f["gender"] = float(round(f["gender"], 2))
                    f["age"] = float(round(f["age"], 2))
                tweet["faces_predict"] = face_predict
            else:
                tweet["faces_predicted"] = "False"
                tweet["faces_predict"] = []
            #json.dump(tweet, outfile)
            tweets.append(tweet)
        json.dump(tweets, outfile)
        #raw_data.append(tweet)
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")
Example #9
0
    for img in list(row['urls']):

        # Evade HTTP 404 Error

        try:
            req = urlopen(img)
            arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
            image = cv2.imdecode(arr, -1)

            if np.all(image == no_profile):
                tcnt += 1
                ncnt += 1
                continue

            face = agender.detect_genders_ages(image)

            # Face Recognition Failed

            if len(face) == 0:
                continue

        # Male

            elif face[0]['gender'] <= 0.5:
                mcnt += 1
                tcnt += 1

        # Female

            elif face[0]['gender'] > 0.5:
Example #10
0
    are_matches = [closest_distances[0][i][0] <= distance_threshold for i in range(len(X_face_locations))]

    # Predict classes and remove classifications that aren't within the threshold
    return [(pred, loc) if rec else ("unknown", loc) for pred, loc, rec in zip(knn_clf.predict(faces_encodings), X_face_locations, are_matches)]



cap = cv2.VideoCapture(0)
cap.set(3, 640)
cap.set(4, 480)
nameold=[]
while 1:
    
    ret,img = cap.read()
    if ret:
        faces = agender.detect_genders_ages(img)

        for face in faces:
            size=[face['width'],face['height'],face['top'],face['left']]
            #print(faces)
            gender=round(face['gender'])
            age=face['age']
            #print(gender)
            if gender>0:
                gender='female'
            else:
                gender='male'
            full_file_path=(size[3],size[2]),(size[3]+size[1],size[2]+size[0])
            predictions = predict(img,full_file_path, model_path="trained_knn_model.clf")
             # Print results on the console
            for name, (top, right, bottom, left) in predictions:
# -*- 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
Example #12
0
    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() 
# see available options in __init__() src

faces_onder_10 = agender.detect_genders_ages(cv2.imread("Onder_10.png"))
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:
        b = get_all_images(i)
        print("no face detected")

    try:
        for data in faces:
            for key in data:
                if (key == 'gender' or key == 'age'):
                    if key == 'gender':
                        gen = data[key]
                    if key == 'age':
                        age = data[key]
        gnum.append(gen)
        ages.append(age)
        print("Male" if gen < 0.5 else "Female", '%.4s' % age, i)

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'
    else:
Example #15
0
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]:
                if value == "age":
                    if faces[int_index][value] <= 25:
                        age_values.append("Cat-01")
                    elif faces[int_index][value] <= 50:
                        age_values.append("Cat-02")
                    else:
                        age_values.append("Cat-03")
Example #16
0
# -*- 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"))