Esempio n. 1
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()
Esempio n. 2
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
Esempio n. 3
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
Esempio n. 4
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
Esempio n. 5
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')