def test_passes_required_arguments_in_payload_as_json_when_image_is_file( self, post_mock): post_mock.return_value.status_code = 200 with mock.patch('builtins.open', mock.mock_open(read_data=str.encode('test'))): with open('/a/image/file.jpg', 'rb') as image_file: image_file.__class__ = BufferedReader kairos_face.recognize_face('gallery', file=image_file) _, kwargs = post_mock.call_args expected_payload = {'image': 'dGVzdA==', 'gallery_name': 'gallery'} self.assertTrue('json' in kwargs) self.assertEqual(expected_payload, kwargs['json'])
def test_passes_additional_arguments_in_payload(self, post_mock): post_mock.return_value.status_code = 200 additional_arguments = {'max_num_results': '5', 'selector': 'EYES'} kairos_face.recognize_face('gallery', url='an_image_url.jpg', additional_arguments=additional_arguments) _, kwargs = post_mock.call_args passed_payload = kwargs['json'] self.assertTrue('max_num_results' in passed_payload) self.assertEqual('5', passed_payload['max_num_results']) self.assertTrue('selector' in passed_payload) self.assertEqual('EYES', passed_payload['selector'])
def test_passes_required_arguments_in_payload_as_json_when_image_is_file(self, post_mock): post_mock.return_value.status_code = 200 with mock.patch('builtins.open', mock.mock_open(read_data=str.encode('test'))): with open('/a/image/file.jpg', 'rb') as image_file: image_file.__class__ = BufferedReader kairos_face.recognize_face('gallery', file=image_file) _, kwargs = post_mock.call_args expected_payload = { 'image': 'dGVzdA==', 'gallery_name': 'gallery' } self.assertTrue('json' in kwargs) self.assertEqual(expected_payload, kwargs['json'])
def dashboard(): if request.method == 'POST': print("<h1>in file</h1>") cam = cv2.VideoCapture(0) frame = cam.read()[1] cv2.imwrite('face2.jpg', frame) cam.release() emaill = request.form['email'] passwordd = request.form['password'] cursor.execute( 'select * from flask_use2 where email="%s" and password="******"' % (emaill, passwordd)) login_details = cursor.fetchall() recognized_faces = kf.recognize_face(file='face2.jpg', gallery_name='a-gallery') status = recognized_faces['images'][0]['transaction']['status'] if len(login_details) == 0: return '<h1>Unregistered E-mail or Password</h1>' else: if status == "success": os.system("mpg321 dash.wav") return render_template('dashboard.html') elif status == "failure": os.system("mpg321 not_reg.wav") return "<h1>Face not registered</h1>" else: return "Error please retry" else: return 'sss'
def recognize(facePhoto=None): try: #dict_responJSON = {} dict_responJSON = kairos_face.recognize_face( file=facePhoto, gallery_name=face_gal_name) """ loop over images object, find transaction with status=success """ dict_faces = {'cnt': 0} #face_count = 0 faces = dict_responJSON['images'] for idx in faces: if idx['transaction']['status'] == 'success': #face_count++ dict_faces['cnt'] = 1 dict_faces['result'] = idx['transaction'] #print(idx['transaction']) break dict_responJSON = dict_faces except Exception, err: if err.__class__ == kairos_face.exceptions.ServiceRequestError: dict_responJSON = { 'error': err.response_msg['Errors'][0]['Message'] } else: dict_responJSON = {'error': str(err)}
def test_returns_matching_images(self): response_body = { "images": [{ "time": 2.86091, "transaction": { "status": "Complete", "subject": "test2", "confidence": "0.802138030529022", "gallery_name": "gallerytest1", }, "candidates": [{ "test2": "0.802138030529022", "enrollment_timestamp": "1416850761" }, { "elizabeth": "0.602138030529022", "enrollment_timestamp": "1417207485" }] }] } responses.add(responses.POST, 'https://api.kairos.com/recognize', status=200, body=json.dumps(response_body)) face_candidates_subjects = kairos_face.recognize_face( 'gallery_name', url='an_image_url.jpg') self.assertEqual(2, len(face_candidates_subjects)) self.assertEqual('test2', face_candidates_subjects[0].subject) self.assertEqual(0.802138030529022, face_candidates_subjects[0].confidence) self.assertEqual('elizabeth', face_candidates_subjects[1].subject) self.assertEqual(0.602138030529022, face_candidates_subjects[1].confidence)
def recog_face_fn(img_path): # Recognizing from a file recognized_faces = kf.recognize_face(file=img_path, gallery_name='students') print(recognized_faces)
def test_passes_additional_arguments_in_payload(self, post_mock): post_mock.return_value.status_code = 200 additional_arguments = { 'max_num_results': '5', 'selector': 'EYES' } kairos_face.recognize_face('gallery', url='an_image_url.jpg', additional_arguments=additional_arguments) _, kwargs = post_mock.call_args passed_payload = kwargs['json'] self.assertTrue('max_num_results' in passed_payload) self.assertEqual('5', passed_payload['max_num_results']) self.assertTrue('selector' in passed_payload) self.assertEqual('EYES', passed_payload['selector'])
def test_returns_transaction_failure_when_face_is_not_recognized(self): response_body = { "images": [{ "time": 6.43752, "transaction": { "status": "failure", "message": "No match found", "gallery_name": "gallery_name" }, }] } responses.add(responses.POST, 'https://api.kairos.com/recognize', status=200, body=json.dumps(response_body)) face_candidates_subjects = kairos_face.recognize_face( 'gallery_name', url='an_image_url.jpg') self.assertEquals(1, len(face_candidates_subjects['images'])) image_response = face_candidates_subjects['images'][0] self.assertEquals('failure', image_response['transaction']['status']) self.assertEquals('No match found', image_response['transaction']['message'])
def processImage(): latestStill( "http://192.168.1.9:88/cgi-bin/CGIProxy.fcgi?cmd=snapPicture2&usr=nuvision&pwd=nuvision" ) recognized_faces = "" try: data = kairos_face.recognize_face(file=latestImage, gallery_name='nuvision') print data #status =data[u'images'][0][u'transaction'][u'topLeftY'] topLeftY = data[u'images'][0][u'transaction'][u'topLeftY'] topLeftX = data[u'images'][0][u'transaction'][u'topLeftX'] width = data[u'images'][0][u'transaction'][u'width'] height = data[u'images'][0][u'transaction'][u'height'] person = data[u'images'][0][u'transaction'][u'subject_id'] still = Image.open(latestImage) banked = still.crop( (topLeftX, topLeftY, topLeftX + width, topLeftY + height)) scale = 64.0 / width banked = banked.resize((int(scale * width), int(scale * height))) # scaled = banked.thumbnail(100, Image.ANTIALIAS) banked.save(output + person + "Banked.jpg") app.sendCommandAPI(person, output) print data print "Recognized " + person + ". Hi " + person + "!" except Exception as e: print e print "No faces recognized."
def check_face(): save_image(request.form['image'], 'face.jpg') response = kairos_face.recognize_face(file='face.jpg', gallery_name='hackathon') print(response) match = response['images'][0]['candidates'][0] print(match) return match['subject_id']
def recognize(request): rec = '' path = '' can_name = '' can_loc = '' can_des = '' can_date = '' captured = False while not captured: try: if request.method == 'POST' and request.FILES['image']: myfile = request.FILES['image'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) global recognized_faces recognized_faces = kairos_face.recognize_face( file=BASE_DIR + "/media/" + fs.url(filename), gallery_name='a-gallery') captured = True sub_id = recognized_faces['images'][0]['candidates'][0][ 'subject_id'] obj = Details.objects.get(pk=sub_id) path = str(obj.image) can_name = obj.name can_loc = obj.location can_des = obj.description can_date = obj.date rec = recognized_faces['images'][0]['candidates'][0][ 'confidence'] * 100 os.remove("media/" + fs.url(filename)) return render( request, 'recognize.html', { 'rec': rec, 'path': path, 'name': can_name, 'loc': can_loc, 'des': can_des, 'date': can_date }) except kairos_face.exceptions.ServiceRequestError: messages.add_message(request, messages.ERROR, 'Error occurred') os.remove("media/" + fs.url(filename)) return render(request, 'recognize.html') except FileNotFoundError: messages.add_message(request, messages.ERROR, 'Please enter the correct file type') os.remove("media/" + fs.url(filename)) return render(request, 'recognize.html') except MultiValueDictKeyError: messages.add_message(request, messages.ERROR, 'No data present in database') os.remove("media/" + fs.url(filename)) return render(request, 'recognize.html') except KeyError: messages.add_message(request, messages.ERROR, 'No matching details found') os.remove("media/" + fs.url(filename)) return render(request, 'recognize.html')
def already_registered(): recognized_faces = kf.recognize_face(file=img_path, gallery_name='a-gallery') status = recognized_faces['images'][0]['transaction']['status'] if status == "success": return True elif status == "failure": return False else: return "Error"
def recog(image): '''Takes only one argument image=image_path''' # Recognizing from an URL # recognized_faces = kf.recognize_face(url='', gallery_name='test') # Recognizing from a file #passing image_path of the image which is to be recognized, gallery _name: to search in which gallery, threshold: confidence value, only give success result for match above this level recognized_faces = kf.recognize_face( file=image, gallery_name='test', additional_arguments={"threshold": "0.50"}) print(recognized_faces)
def dashboard(): print("hello") recognized_faces = kf.recognize_face(file='index.jpeg', gallery_name='a-gallery') status = recognized_faces['images'][0]['transaction']['status'] if status == "success": return render_template('dashboard.html') elif status == "failure": return False else: return "Error" return render_template('capture.html')
def recognize_image(path): recognized_image = kairos_face.recognize_face(file=path, gallery_name='Demo') print(recognized_image) data = json.dumps(recognized_image) # for dict from data dic_data = json.loads(data) # getting status out of data status = (dic_data['images'][0]['transaction']['status']) enroll(status, path)
def recognisePerson(testdata, database_naam, NumberOfFaces, verbose, chillMode): correct = 0 false = 0 total = len(testdata) pbar = tqdm(total = len(testdata)) for i, test in enumerate(testdata): if chillMode: time.sleep(2) try: data = kairos_face.recognize_face(file=test, gallery_name=database_naam) #print(data) #print('---------------------------------------------------------------') # Do something with the returned data: original_face_number = 0 x = 1 while x < NumberOfFaces: if x <= int(test[8:12]) <= x+20: original_face_number = x break else: x += 20 if 'images' in data: resultData = int(data['images'][0]['transaction']['subject_id']) if verbose: print "\nI recognised the image as: {} \t | It has to be between: {} and {} \t | Original: {}\n".format(resultData, original_face_number, original_face_number+20, test[8:12]) if resultData >= original_face_number and resultData <= original_face_number + 20: correct += 1 else: false += 1 if verbose: print(bcolors.BOLD + 'Intermediar results: ' + bcolors.OKGREEN + '{} correct'.format(correct) + bcolors.ENDC + ' -- ' + bcolors.FAIL + '{} wrong.\n'.format(false) + bcolors.ENDC) except Exception as e: if verbose: print(bcolors.FAIL + "ERROR RECOGNISE PERSON: {}".format(e) + bcolors.ENDC) else: pass if chillMode: time.sleep(30) pbar.update() pbar.close() return correct, len(testdata)
def already_registered(img_path='user_img.png') : #recognizing registered faces recognized_faces = kf.recognize_face(file=img_path, gallery_name='students') status = recognized_faces['images'][0]['transaction']['status'] if status == 'success' : return get_id(recognized_faces) elif status == 'failure' : return None else : return "Retake"
def already_registered(img_path='user_img.png') : #recognizing registered faces recognized_faces = kf.recognize_face(file=img_path, gallery_name='students') status = recognized_faces['images'][0]['transaction']['status'] if status == 'success' : return True elif status == 'failure' : return False else : print('Error in recognising')
def recognizeFile(path): try: recog = kairos_face.recognize_face(file=path, gallery_name="whitelist") found = recog['images'][0]['transaction']['status'] if found == 'success': print('Face found in Whitelist') person = recog['images'][0]['transaction']['subject_id'] confidence = recog['images'][0]['transaction']['confidence'] url = recog['uploaded_image_url'] print(found) print("The person is " + person + " with %d percent confidence in whitelist." % (confidence * 100)) return (1, person, int(confidence), url) else: recog = kairos_face.recognize_face(file=path, gallery_name="blacklist") found = recog['images'][0]['transaction']['status'] if found == 'success': print('Face found in Blacklist') url = recog['uploaded_image_url'] person = recog['images'][0]['transaction']['subject_id'] confidence = float( recog['images'][0]['transaction']['confidence']) print(found) print("The person is " + person + " with %d percent confidence in blacklist." % (confidence * 100)) return (0, str(person), confidence * float(100), url) else: return (2, None, None, None) except kairos_face.exceptions.ServiceRequestError: print('gallery not found') return (2, None, None, None) except: print('ERROR!!')
def test_returns_matching_images(self): response_body = { 'images': [ { 'time': 2.86091, 'transaction': { 'status': 'Complete', 'subject': 'test2', 'confidence': '0.802138030529022', 'gallery_name': 'gallerytest1', }, 'candidates': [ { 'test2': '0.802138030529022', 'enrollment_timestamp': '1416850761' }, { 'elizabeth': '0.602138030529022', 'enrollment_timestamp': '1417207485' } ] } ] } responses.add(responses.POST, 'https://api.kairos.com/recognize', status=200, body=json.dumps(response_body)) face_candidates_subjects = kairos_face.recognize_face('gallery_name', url='an_image_url.jpg') self.assertEqual(2, len(face_candidates_subjects['images'][0]['candidates'])) image_response = face_candidates_subjects['images'][0] self.assertEquals('Complete', image_response['transaction']['status']) candidates = image_response['candidates'] self.assertEquals(2, len(candidates)) self.assertIn('test2', candidates[0]) self.assertIn('0.802138030529022', candidates[0].values()) self.assertIn('elizabeth', candidates[1]) self.assertIn('0.602138030529022', candidates[1].values())
def doWinston(dct): global location idd = -1 dct['frames'][0]['people'][0]['location'] = location try: #Try to find current person in database, if not, enroll them ans = kairos_face.recognize_face(file='image.png', gallery_name='test') if 'Errors' in ans: print ans['Errors'][0]['Message'] elif len(ans['images'][0]['candidates']) == 0: print "Nobody found! Time to enroll!" idd = hex(random.randint(1, 100000000000)) enr = kairos_face.enroll_face(file='image.png', subject_id=idd, gallery_name='test') dct['frames'][0]['people'][0]['id'] = idd requests.post( "https://za4fvvbnvd.execute-api.us-east-2.amazonaws.com/Hackathon/emotions", json=dct) else: idd = ans['images'][0]['transaction']['subject_id'] print idd + " welcome back!" dct['frames'][0]['people'][0]['id'] = idd requests.post( "https://za4fvvbnvd.execute-api.us-east-2.amazonaws.com/Hackathon/emotions", json=dct) except: #Runs if gallery not found (database dumped) print "Nobody found! Time to enroll!" try: idd = hex(random.randint(1, 100000000000)) enr = kairos_face.enroll_face(file='image.png', subject_id=idd, gallery_name='test') dct['frames'][0]['people'][0]['id'] = idd requests.post( "https://za4fvvbnvd.execute-api.us-east-2.amazonaws.com/Hackathon/emotions", json=dct) except Exception, e: print e
def test_returns_transaction_failure_when_face_is_not_recognized(self): response_body = { 'images': [{ 'time': 6.43752, 'transaction': { 'status': 'failure', 'message': 'No match found', 'gallery_name': 'gallery_name' }, }] } responses.add(responses.POST, 'https://api.kairos.com/recognize', status=200, body=json.dumps(response_body)) face_candidates_subjects = kairos_face.recognize_face('gallery_name', url='an_image_url.jpg') self.assertEquals(1, len(face_candidates_subjects['images'])) image_response = face_candidates_subjects['images'][0] self.assertEquals('failure', image_response['transaction']['status']) self.assertEquals('No match found', image_response['transaction']['message'])
def analyzeFrame(self, image_path): print("Analyzing Frame:") if not os.path.exists('image/glass_face'): os.mkdir('image/glass_face') image_paths = glob.glob(os.path.join('image/glass_face/', "*")) # get the number of faces currently stored in the folder 'image/glass_face/' as face_count # lately, the cropped face detected in the image referred by image_path will be saved as face_count.jpg face_count = len(image_paths) img = cv2.imread(image_path, 3) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = self.faceCascade.detectMultiScale(gray, 1.3, 5) # zero or multiple faces detected if len(faces) != 1: print("Error: " + str(len(faces)) + " faces detected!\n") return "ZeroOrMultipleFaces" # one face detected else: (x, y, w, h) = faces[0] crop_img = img[y:y + h, x:x + w] # write cropped face image output_path = 'image/glass_face/' + str(face_count) + '.jpg' cv2.imwrite(output_path, crop_img) # recognizing cropped face image print("Recognizing: ") recognize_face_response = kairos_face.recognize_face( file=output_path, gallery_name=self.targetGallery) #print(recognize_face_response) if 'candidates' in recognize_face_response['images'][0].keys(): # Kairos knows the face subject_id = recognize_face_response['images'][0][ 'candidates'][0]['subject_id'] print("Name detected: " + subject_id + '\n') # return the name given by Kairos return subject_id else: # Kairos doesn't know the face return "Unknown"
def showRefugee(request): if request.method == "POST": form = RefugeeForm(request.POST, request.FILES) if form.is_valid(): refugee = form.save(commit=False) refImage = request.FILES["refImage"] fs = FileSystemStorage() filePath = os.path.dirname( os.path.dirname(os.path.abspath(__file__))) filePath = filePath + '/media/' + str( refugee.pk) + refImage.name[-4:] fs.save(filePath, refImage) recognized_faces = kairos_face.recognize_face( file=filePath, gallery_name=gallery_name) print(recognized_faces) try: confidence = recognized_faces["images"][0]["candidates"][0][ "confidence"] if (confidence > 0.7): print("You are fraud") form = RefugeeForm() return render(request, 'RefugeeForm.html', {'form': form}) except KeyError: pass kairos_face.enroll_face(file=filePath, subject_id=str(refugee.pk), gallery_name=gallery_name) refugee.bID = request.user.username refugee.save() return redirect('/bo/refugeeCard/' + str(refugee.pk)) else: form = RefugeeForm() return render(request, 'RefugeeForm.html', {'form': form})
def recognize(self): import kairos_face from kairos_face.exceptions import ServiceRequestError try: response = kairos_face.recognize_face( url=self.image_1.url, gallery_name=settings.KAIROS_GALLERY) except ServiceRequestError as e: return { 'prof': None, 'message': 'No faces detected', 'status': 400 } print(response) if len(response['images']) == 0: return {'prof': None, 'message': '', 'status': 400} if response['images'][0]['transaction']['status'] == 'success': prof_id = response['images'][0]['transaction']['subject_id'] self.recognized_user_id = prof_id self.recognition_successful = True try: prof = Consumer.objects.get(pk=prof_id) self.recognized_profile = prof self.save() return {'prof': prof, 'message': 'User found!', 'status': 200} except Consumer.DoesNotExist: self.save() return { 'prof': None, 'message': 'No matching user found', 'status': 404 } else: return {'prof': None, 'message': 'User Not Found', 'status': 404}
def test_throws_exception_when_both_file_and_url_are_passed(self): with self.assertRaises(ValueError): kairos_face.recognize_face('gallery', url='an_image_url.jpg', file='/path/tp/image.jpg')
def test_throws_exception_when_file_is_empty_string(self): with self.assertRaises(ValueError): kairos_face.recognize_face('gallery', file='')
def test_throws_exception_when_app_key_is_not_set(self): kairos_face.settings.app_key = None with self.assertRaises(kairos_face.SettingsNotPresentException): kairos_face.recognize_face('gallery', url='an_image_url.jpg')
camera = PiCamera() camera.resolution = (640, 480) camera.framerate = 32 rawCapture = PiRGBArray(camera, size=(640, 480)) time.sleep(.1) #capture a clean image and write it to the current folder cont = 'y' for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): image = frame.array cv2.imwrite('image.png', image) rawCapture.truncate(0) try: #Try to find current person in database, if not, enroll them ans = kairos_face.recognize_face(file='image.png', gallery_name='test') if 'Errors' in ans: print ans['Errors'][0]['Message'] elif len(ans['images'][0]['candidates']) == 0: print "Nobody found! Time to enroll!" enr = kairos_face.enroll_face( file='image.png', subject_id=raw_input("What is your name: "), gallery_name='test') else: print "Hello " + ans['images'][0]['transaction']['subject_id'] + "!" except: #Runs if gallery not found (database dumped) print "Nobody found! Time to enroll!" try: enr = kairos_face.enroll_face(
import kairos_face as kf kf.settings.app_id = 'ypur app id' kf.settings.app_key = 'your app key' # galleries_list=kf.get_galleries_names_list() # # print(galleries_list) # # gallery_sub=kf.get_gallery('a-gallery') # # print(gallery_sub) recognized_faces = kf.detect_face(file='harry-meghan-15.jpg') detected_faces = kf.recognize_face(file='harry-meghan-15.jpg', gallery_name='a-gallery')
#%matplotlib inline kairos_face.settings.app_id = '9311364a' kairos_face.settings.app_key = '21645ea39b84fccd009e59f1114ce9b8' #putting in training data for i in range(1, 7): fname = 'kim' + str(i) + '.jpg' print(fname) if os.path.exists(fname) != True: print('no such file') kairos_face.enroll_face(file=fname, subject_id='Kim Jong Un', gallery_name='kju-gallery') recognized_faces = kairos_face.recognize_face(file='kjursj.jpg', gallery_name='kju-gallery') image = face_recognition.load_image_file('kjursj.jpg') for i in range(len(recognized_faces['images'])): a_face = recognized_faces['images'][i]['transaction'] status = a_face['status'] top = a_face['topLeftY'] bottom = a_face['topLeftY'] + a_face['height'] left = a_face['topLeftX'] right = a_face['topLeftX'] + a_face['width'] face_image = image[top:bottom, left:right] pil_image = Image.fromarray(face_image) file_name = 'image' + str(i) + '.jpg' pil_image.save(file_name)
def recognize(request): try: cur = connection.cursor() logging.info('DB connected') except: logging.info('Db connection error') kairos_face.settings.app_id = 'Your App ID' kairos_face.settings.app_key = 'Your App key' if request.method == 'POST': #POST goes here . is_ajax is must to capture ajax requests. if request.is_ajax(): gallery = request.POST.get('gallery') image = request.POST.get('image') try: recognized_faces = kairos_face.recognize_face( file=image, gallery_name=gallery) uname = recognized_faces['images'][0]['candidates'][0][ 'subject_id'] result = 'success' except: result = 'error' uname = '' if result == 'success': cur.execute(''' select * from cv where uname=%s''', (uname, )) res = cur.fetchall() newlist = [ele for ele in res[0]] email = str(newlist[1]) designation = str(newlist[3]) team = str(newlist[4]) qresult = 'success' else: qresult = 'error' email = '' designation = '' team = '' detected_faces = kairos_face.detect_face(file=image) gen = detected_faces['images'][0]['faces'][0]['attributes'][ 'gender']['type'] age = detected_faces['images'][0]['faces'][0]['attributes']['age'] gender = '' if gen == 'M': gender = 'Male' else: gender = 'Female' data = { 'uname': uname, 'email': email, 'designation': designation, 'team': team, 'result': result, 'qresult': qresult, 'gender': gender, 'age': age } return JsonResponse(data) return render(request, 'recognize.html')