Пример #1
0
def recognizeFace(photo_url):
	from face_client import FaceClient
	client = FaceClient(settings.FACES_API,settings.FACES_SECRET)
	try:
		photo = client.faces_detect(photo_url)['photos'][0]
	except:
		return False
	if len(photo['tags']) > 0:
		return getFace(photo)
	else:
		return False
Пример #2
0
 def __init__(self, api_key, api_secret):
     """
     Python wrapper for the Skybiometry API
     :param api_key: The authorization key of the Skybiometry API
     :param api_secret: The secret of the Skybiometry API
     """
     self._face_client = FaceClient(api_key, api_secret)
Пример #3
0
def emo_proc(data, coll_name):
    coll_name += '_emo'
    client = FaceClient('3662cdd27df1426c9d3634cbc47342d5', '8606203f879b4d9e956e691fae0ac6d3')
    i = 0
    k = 0
    for each in data:
        try:
            result = client.faces_detect(each.img_url)
        except Exception as err:
            if str(err).find("202") != -1:
                print "limit err"
                if k==0:
                    time.sleep(3600)
                    k = 1
                else:
                    time.sleep(60)
                    k = 0
        else:
            write_to_db(coll_name, result)
Пример #4
0
def recognize_photo(request_id):
    """
        This task execute the recognizer function
    """
    request = RequestRecognizer.objects.get(id=request_id)
    request.imagenByteArray = request.image_to_binary
    request.save()

    # Create one instance of library for connect to webservice
    client = FaceClient(
        '245c8bb50b2f42228a6a998863f5a1e0',
        'c1800f96cf0647fb8412ae8d3dae1202',
    )

    # Call function web service
    result = client.faces_recognize(
        'all',
        file=request.image,
        aggressive=True,
        namespace='CompareFaces',
    )

    # Validate if there are results
    if result['photos'][0]['tags']:
        recognize = None
        level_recognize = ''

        for item in result['photos'][0]['tags'][0]['uids']: # If exists coincidences
            if item['confidence'] >= 80:
                level_recognize = LEVEL_RECOGNIZE_HIGH
            elif item['confidence'] >= 60 and item['confidence'] < 80:
                level_recognize = LEVEL_RECOGNIZE_MEDIUM
            if not recognize and item['confidence'] < 60:
                request.access = False
                request.status = DEACTIVE_STATUS
            if not recognize or (recognize and item['confidence'] > recognize['confidence']):
                recognize = item
                recognize['uid'] = recognize['uid'].split('@')[0]
                recognize['level'] = level_recognize
        request.result_recognizer = recognize
        request.save()
Пример #5
0
def training(request):

    if not request.user.is_superuser:
        return HttpResponseForbidden('Only for Superuser')

    if request.method == 'POST':

        f = request.POST
        form = ImageUploadForm(request.POST, request.FILES)
        if form.is_valid():

            if not Senior.objects.filter(student_id=f['student_id']):
                senior = Senior.objects.create(
                    name=f['name'],
                    image=form.cleaned_data['image'],
                    student_id=f['student_id']
                    )
                senior.save()
            else:
                senior = Senior.objects.get(student_id=f['student_id'])
                senior.image = form.cleaned_data['image']
                senior.save()

            image_url = 'http://150.95.135.222:8000' + senior.image.url

            client = FaceClient('ac38c745411845ce89698e1e2469df79', '9d70c1da17fd49609327c8ca154061f1')
            response = client.faces_detect(image_url)
            tid = response['photos'][0]['tags'][0]['tid']
            client.tags_save(tids=tid, uid=f['student_id']+'@senior', label=f['student_id'])
            result = client.faces_train(f['student_id']+'@senior')

            return render(request, 'software/training.html', {'result': result})

        else:
            return HttpResponseForbidden('form is invalid')

    else:
        return render(request, 'software/training.html', {})
Пример #6
0
def recognizeFace(theImg,filenameFull):
	font = ImageFont.truetype("/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans-Bold.ttf", 14)
	theFileLocation =  "http://" + config.publicIP + "/temp.jpg"
	client = FaceClient(keyring.get_password('skybio','api_key'),keyring.get_password('skybio','api_secret'))
	img = Image.open(theImg)
	width, height = img.size
	draw = ImageDraw.Draw(img)
	print theFileLocation
	photo = client.faces_recognize('all',theFileLocation, namespace = 'python')
	print photo
	# Number of people in photo
	numFaces = len(photo['photos'][0]['tags'])
	print "Detected " + str(numFaces) + " faces."
	textCaption = ""
	iii=0
	theSpeech = ""
	while iii<numFaces:
		for person in config.personList:
#		for j, person in enumerate(personList):
			try:
				theId = photo['photos'][0]['tags'][iii]['uids'][0]['uid']
				foundName = theId
				print "I see " + foundName
				xPos = width*(int(photo['photos'][0]['tags'][iii]['eye_right']['x']))/100
				yPos = height*(int(photo['photos'][0]['tags'][iii]['eye_right']['y']))/100
				if person.name in foundName: #and photo['photos'][0]['tags'][iii]['attributes']['gender']['value'] == person.gender:
					theSpeech = theSpeech + "%s" % person.greeting
					
					timeDifference = datetime.datetime.now() - person.lastSeen
					person.lastSeen = datetime.datetime.now()
					#personList[j].lastSeen = person.lastSeen
					days = math.floor(timeDifference.total_seconds() / 60 / 60 / 24)
					hours = math.floor(timeDifference.total_seconds() / 60 / 60	)	
					minutes = math.floor(timeDifference.total_seconds() / 60 )	
					if days > 0:
						theSpeech = theSpeech + "It's been %d days since I have seen you, %s. " % (days,person.name)
					elif hours > 4:
						theSpeech = theSpeech +  "It's been %d hours since I have seen you, %s. " % (hours,person.name)
					elif minutes > 0:
						theSpeech = theSpeech +  "It's been %d minutes since I have seen you, %s. " % (minutes,person.name)
					draw.text((xPos, yPos),person.name,(255,255,0),font=font)
					draw.text((0, 0),time.strftime("%c"),(255,255,0),font=font)
					collection = ['eyes','sadness','mood','glasses']
					for x in collection:
						try:
							eyes = photo['photos'][0]['tags'][iii]['attributes'][x]['value']
							conf = photo['photos'][0]['tags'][iii]['attributes'][x]['confidence']
							if conf > 20:
								print " " + x + " = " + eyes
								yPos = yPos + 20
								draw.text((xPos, yPos)," " + x + ": " + eyes,(255,255,0),font=font)
								if x == 'mood':
									theSpeech = theSpeech + "Why are you " + eyes + "? "		
						except:
							print "No " + x
			except:
				print "Error locating face in person database."
				print "Unexpected error:", sys.exc_info()[0]
				raise
		iii = iii + 1
	
	if len(theSpeech)>2: # proxy for if something happened
		img.save(filenameFull)
		img.save("/var/www/face.jpg")
		pickle.dump(config.personList, open("ai_data/personlist.p","wb") )
	return theSpeech
from std_srvs.srv import Empty

import numpy as np
import cv2
import os
from datetime import datetime

import dlib
import openface

from face_client import FaceClient

from timeout import Timeout

# For attributes
face_client = FaceClient('69efefc20c7f42d8af1f2646ce6742ec',
                         '5fab420ca6cf4ff28e7780efcffadb6c')


def _external_request_with_timeout(buffers):
    timeout_duration = 60
    rospy.loginfo("Trying external API request for %d seconds",
                  timeout_duration)
    timeout_function = Timeout(face_client.faces_recognize, timeout_duration)
    return timeout_function(buffers)


def _set_label(img, label, origin):
    font = cv2.FONT_HERSHEY_SIMPLEX
    scale = 0.4
    thickness = 1
Пример #8
0
# Copyright (c) 2010, 2011, Tomaž Muraus
# All rights reserved.

from face_client import FaceClient
import json
import csv
import time

client = FaceClient('88c2f662703642d99d67bce4400bbebf', 'd5d89a3b8a8c42dfafb94a19728a183d')

# print response['photos'][0]['tags'][0]['attributes']['gender']['value']
# print response['photos'][0]['tags'][0]['attributes']['gender']['confidence']

url_list =[]

with open('final_male.txt','r') as f:
    for line in f.readlines():
        url_list.append(line.strip('\n'))

if __name__ == '__main__':

    csv_file = open('sky_male.csv','ab')
    writer = csv.writer(csv_file)
    writer.writerow(["ID","URL","GENDER","CONFIDENCE"])

    total_count = 1
    for url in url_list:
        try:
            response = client.faces_detect(url)
            # print response
            if response['photos'][0]['tags'] == []:
Пример #9
0
import argparse
import vision
import track

parser = argparse.ArgumentParser()
parser.add_argument("-c",
                    "--conf",
                    default="./conf.json",
                    help="path to JSON config file")
args = vars(parser.parse_args())

conf = json.load(open(args["conf"]))

API_KEY = 'egk0ko9neatt4ftsgmhsmklf2r'
API_SECRET = '67doedp6s4dcnm5kmuhkgetj8p'
client = FaceClient(API_KEY, API_SECRET)
metrics = ['mood', 'smiling']

domain_name = 'sherrywangspi.ddns.net'
filename = "/var/www/html/temp.jpg"
img_addr = 'http://{}/temp.jpg'.format(domain_name)

ref_frame = cv2.imread(conf['ref_img'])
KNOWN_PIXEL_WIDTH = track.calculate_pixel_width(ref_frame)

camera = picamera.PiCamera()
camera.resolution = conf['resolution']
camera.framerate = conf['frame_rate']
rawCapture = PiRGBArray(camera, size=conf['resolution'])
time.sleep(conf["camera_warmup_time"])
Пример #10
0
def recognizeFace(theImg, filenameFull):
    font = ImageFont.truetype(
        "/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans-Bold.ttf", 14)
    theFileLocation = "http://" + config.publicIP + "/temp.jpg"
    client = FaceClient(keyring.get_password('skybio', 'api_key'),
                        keyring.get_password('skybio', 'api_secret'))
    img = Image.open(theImg)
    width, height = img.size
    draw = ImageDraw.Draw(img)
    print theFileLocation
    photo = client.faces_recognize('all', theFileLocation, namespace='python')
    print photo
    # Number of people in photo
    numFaces = len(photo['photos'][0]['tags'])
    print "Detected " + str(numFaces) + " faces."
    textCaption = ""
    iii = 0
    theSpeech = ""
    while iii < numFaces:
        for person in config.personList:
            #		for j, person in enumerate(personList):
            try:
                theId = photo['photos'][0]['tags'][iii]['uids'][0]['uid']
                foundName = theId
                print "I see " + foundName
                xPos = width * (int(
                    photo['photos'][0]['tags'][iii]['eye_right']['x'])) / 100
                yPos = height * (int(
                    photo['photos'][0]['tags'][iii]['eye_right']['y'])) / 100
                if person.name in foundName:  #and photo['photos'][0]['tags'][iii]['attributes']['gender']['value'] == person.gender:
                    theSpeech = theSpeech + "%s" % person.greeting

                    timeDifference = datetime.datetime.now() - person.lastSeen
                    person.lastSeen = datetime.datetime.now()
                    #personList[j].lastSeen = person.lastSeen
                    days = math.floor(timeDifference.total_seconds() / 60 /
                                      60 / 24)
                    hours = math.floor(timeDifference.total_seconds() / 60 /
                                       60)
                    minutes = math.floor(timeDifference.total_seconds() / 60)
                    if days > 0:
                        theSpeech = theSpeech + "It's been %d days since I have seen you, %s. " % (
                            days, person.name)
                    elif hours > 4:
                        theSpeech = theSpeech + "It's been %d hours since I have seen you, %s. " % (
                            hours, person.name)
                    elif minutes > 0:
                        theSpeech = theSpeech + "It's been %d minutes since I have seen you, %s. " % (
                            minutes, person.name)
                    draw.text((xPos, yPos),
                              person.name, (255, 255, 0),
                              font=font)
                    draw.text((0, 0),
                              time.strftime("%c"), (255, 255, 0),
                              font=font)
                    collection = ['eyes', 'sadness', 'mood', 'glasses']
                    for x in collection:
                        try:
                            eyes = photo['photos'][0]['tags'][iii][
                                'attributes'][x]['value']
                            conf = photo['photos'][0]['tags'][iii][
                                'attributes'][x]['confidence']
                            if conf > 20:
                                print " " + x + " = " + eyes
                                yPos = yPos + 20
                                draw.text((xPos, yPos),
                                          " " + x + ": " + eyes, (255, 255, 0),
                                          font=font)
                                if x == 'mood':
                                    theSpeech = theSpeech + "Why are you " + eyes + "? "
                        except:
                            print "No " + x
            except:
                print "Error locating face in person database."
                print "Unexpected error:", sys.exc_info()[0]
                raise
        iii = iii + 1

    if len(theSpeech) > 2:  # proxy for if something happened
        img.save(filenameFull)
        img.save("/var/www/face.jpg")
        pickle.dump(config.personList, open("ai_data/personlist.p", "wb"))
    return theSpeech
Пример #11
0
#upload pictures from dir one at a time
for file in captureList:
	#debug later had to hard code this one for some unknown EOL string error
	filename = "C:/facerecog/images/" +file
	response = auth.InsertPhotoSimple(album_url, file, 'FaceRecog', filename, content_type='image/jpeg')
	uploadCount = uploadCount + 1
	
	#Writing to file instead of passing directly into memory not using buffer	
	with open('picasa_response.xml', 'a') as debugUpload:
		debugUpload.write(str(response))
		#Looking for direct URL images of the detected faces
		'''
		Using regex string searching instead because ElementTree 
		child element attribute does not contain end tag needed for easy parsing
		of direct URL image of face to utilize in face training API
		'''
		xmlFile = open('picasa_response.xml', 'r')
		urls = re.findall('ns0:content src="https://\w+.googleusercontent.com/\S+', xmlFile.read())
		scrubURLa = re.sub('ns0:content src="', '', str(urls))
		scrubURLb = re.sub("[\[|\]|\"|\']", '', str(scrubURLa))
		scrubURLc = re.sub(", ", ',', str(scrubURLb))
		faceCompareURL = scrubURLc
	
		#SkyBiometry API Client Object and Auth
		client = FaceClient(skyBiometryAPI_ID, skyBiometryAPI_KEY)

		response = client.faces_recognize('all', faceCompareURL, namespace = 'facetrain')

print response
Пример #12
0
def recognize(request):

    if request.method == 'POST':
        user = request.user
        profile = Profile.objects.get(user=user)

        f = request.POST
        form = ImageUploadForm(request.POST, request.FILES)

        if form.is_valid():
            catching = Catching.objects.create(
                image=form.cleaned_data['image'],
                senior=None,
                profile=profile,
                comment=""
            )
            catching.save()

            image_url = 'http://150.95.135.222:8000' + catching.image.url
            
            client = FaceClient('ac38c745411845ce89698e1e2469df79', '9d70c1da17fd49609327c8ca154061f1')
            result = client.faces_recognize('all', image_url, namespace='senior')

            try:
                student_id1 = result['photos'][0]['tags'][0]['uids'][0]['uid'].split('@')[0]
                confidence1 = result['photos'][0]['tags'][0]['uids'][0]['confidence']
                senior1 = Senior.objects.get(student_id=student_id1)
                senior1_name = senior1.name

                student_id2 = result['photos'][0]['tags'][0]['uids'][1]['uid'].split('@')[0]
                confidence2 = result['photos'][0]['tags'][0]['uids'][1]['confidence']
                senior2 = Senior.objects.get(student_id=student_id2)
                senior2_name = senior2.name

                student_id3 = result['photos'][0]['tags'][0]['uids'][2]['uid'].split('@')[0]
                confidence3 = result['photos'][0]['tags'][0]['uids'][2]['confidence']
                senior3 = Senior.objects.get(student_id=student_id3)
                senior3_name = senior3.name          
            
                catchsenior = f['catchsenior']
     
                if len(result['photos'][0]['tags']) > 1:
                    student_id4 = result['photos'][0]['tags'][1]['uids'][0]['uid'].split('@')[0]
                    confidence4 = result['photos'][0]['tags'][1]['uids'][0]['confidence']
                    senior4 = Senior.objects.get(student_id=student_id4)
                    senior4_name = senior4.name

                    student_id5 = result['photos'][0]['tags'][1]['uids'][1]['uid'].split('@')[0]
                    confidence5 = result['photos'][0]['tags'][1]['uids'][1]['confidence']
                    senior5 = Senior.objects.get(student_id=student_id5)
                    senior5_name = senior5.name

                    student_id6 = result['photos'][0]['tags'][1]['uids'][2]['uid'].split('@')[0]
                    confidence6 = result['photos'][0]['tags'][1]['uids'][2]['confidence']
                    senior6 = Senior.objects.get(student_id=student_id6)
                    senior6_name = senior6.name
                        
                    return render(request, 'software/recognize.html', {'catching': catching,
                                                                       'image_url': image_url,
                                                                       'senior1_name': senior1_name,
                                                                       'confidence1': confidence1,
                                                                       'student_id1': student_id1,
                                                                       'senior2_name': senior2_name,
                                                                       'confidence2': confidence2,
                                                                       'student_id2': student_id2,
                                                                       'senior3_name': senior3_name,
                                                                       'confidence3': confidence3,
                                                                       'student_id3': student_id3,
                                                                       'senior4_name': senior4_name,
                                                                       'confidence4': confidence4,
                                                                       'student_id4': student_id4,
                                                                       'senior5_name': senior5_name,
                                                                       'confidence5': confidence5,
                                                                       'student_id5': student_id5,
                                                                       'senior6_name': senior6_name,
                                                                       'confidence6': confidence6,
                                                                       'student_id6': student_id6,
                                                                       'catchsenior': catchsenior,
                                                                       'person_num': '2',
                                                                      })
                        
                return render(request, 'software/recognize.html', {'catching': catching,
                                                                   'image_url': image_url,
                                                                   'senior1_name': senior1_name,
                                                                   'confidence1': confidence1,
                                                                   'student_id1': student_id1,
                                                                   'senior2_name': senior2_name,
                                                                   'confidence2': confidence2,
                                                                   'student_id2': student_id2,
                                                                   'senior3_name': senior3_name,
                                                                   'confidence3': confidence3,
                                                                   'student_id3': student_id3,
                                                                   'catchsenior': catchsenior,
                                                                   'person_num': '1',
                                                                  })
            except IndexError as err:
                return HttpResponse("Index Error - Please contact to kakaotalk ID : mnmnm059")
            except Exception as err:
                return HttpResponse(str(err) + "- Please contact to kakaotalk ID : mnmnm059")
        else:
            return HttpResponseForbidden('form is invalid')
    else:
        return HttpResponseForbidden('Allowed via POST')