Package: compreface-sdk
CompreFace Python SDKCompreFace Python SDK makes face recognition into your application even easier.Table of contentRequirementsInstallationUsageInitializationAdding faces into a face collectionRecognitionWebcam demoReferenceCompreFace Global ObjectMethodsOptions structureFace Recognition ServiceRecognize Faces from a Given ImageGet Face CollectionAdd an Example of a SubjectList of All Saved Examples of the SubjectDelete All Examples of the Subject by NameDelete an Example of the Subject by IDVerify Faces from a Given ImageGet SubjectsAdd a SubjectList SubjectsRename a SubjectDelete a SubjectDelete All SubjectsFace Detection ServiceDetectFace Verification ServiceVerifyContributingReport BugsSubmit FeedbackLicense infoRequirementsBefore using our SDK make sure you have installed CompreFace and Python on your machine.CompreFacePython(Version 3.7+)CompreFace compatibility matrixCompreFace Python SDK versionCompreFace 0.5.xCompreFace 0.6.x0.1.0✔:yellow_circle:0.6.x:yellow_circle:✔Explanation:✔  SDK supports all functionality from CompreFace.:yellow_circle:  SDK works with this CompreFace version.
In case if CompreFace version is newer - SDK won't support new features of CompreFace. In case if CompreFace version is older - new SDK features will fail.✘ There are major backward compatibility issues. It is not recommended to use these versions togetherInstallationIt can be installed through pip:pipinstallcompreface-sdkUsageAll these examples you can find in repository insideexamplesfolder.InitializationTo start using Python SDK you need to importCompreFaceobject from 'compreface-sdk' dependency.Then you need to init it withurlandport. By default, if you run CompreFace on your local machine, it'shttp://localhostand8000respectively.
You can pass optionaloptionsobject when call method to set default parameters, see reference formore information.After you initializedCompreFaceobject you need to init the service object with theapi keyof your face service. You can use this service object to recognize faces.However, before recognizing you need first to add faces into the face collection. To do this, get the face collection object from the service object.fromcomprefaceimportCompreFacefromcompreface.serviceimportRecognitionServicefromcompreface.collectionsimportFaceCollectionfromcompreface.collections.face_collectionsimportSubjectsDOMAIN:str='http://localhost'PORT:str='8000'API_KEY:str='your_face_recognition_key'compre_face:CompreFace=CompreFace(DOMAIN,PORT)recognition:RecognitionService=compre_face.init_face_recognition(API_KEY)face_collection:FaceCollection=recognition.get_face_collection()subjects:Subjects=recognition.get_subjects()Adding faces into a face collectionHere is example that shows how to add an image to your face collection from your file system:image_path:str='examples/common/jonathan-petit-unsplash.jpg'subject:str='Jonathan Petit'face_collection.add(image_path=image_path,subject=subject)RecognitionThis code snippet shows how to recognize unknown face.image_path:str='examples/common/jonathan-petit-unsplash.jpg'recognition.recognize(image_path=image_path)Webcam demoWebcam demo shows how to use CompreFace Recognition and Detection services using Python SDK.
In both cases, age, gender and mask plugins are applied.Follow thislinkto see the instructions.ReferenceCompreFace Global ObjectGlobal CompreFace Object is used for initializing connection to CompreFace and setting default values for options.
Default values will be used in every service method if applicable.
If the option’s value is set in the global object and passed as a function argument then the function argument value will be used.Constructor:CompreFace(domain, port, options)ArgumentTypeRequiredNotesurlstringrequiredURL with protocol where CompreFace is located. E.g.http://localhostportstringrequiredCompreFace port. E.g.8000optionsobjectoptionalDefault values for face recognition services. See morehere.AllOptionsDictobject can be used in this methodPossible options:OptionTypeNotesdet_prob_thresholdstringminimum required confidence that a recognized face is actually a face. Value is between 0.0 and 1.0limitintegermaximum number of faces on the image to be recognized. It recognizes the biggest faces first. Value of 0 represents no limit. Default value: 0prediction_countintegermaximum number of subject predictions per face. It returns the most similar subjects. Default value: 1face_pluginsstringcomma-separated slugs of face plugins. If empty, no additional information is returned.Learn morestatusbooleanif true includes system information like execution_time and plugin_version fields. Default value is falseExample:fromcomprefaceimportCompreFaceDOMAIN:str='http://localhost'PORT:str='8000'compre_face:CompreFace=CompreFace(domain=DOMAIN,port=PORT,options={"limit":0,"det_prob_threshold":0.8,"prediction_count":1,"face_plugins":"calculator,age,gender,landmarks","status":"true"})MethodsCompreFace.init_face_recognition(api_key)Inits face recognition service object.ArgumentTypeRequiredNotesapi_keystringrequiredFace Recognition Api Key in UUID formatExample:fromcompreface.serviceimportRecognitionServiceAPI_KEY:str='your_face_recognition_key'recognition:RecognitionService=compre_face.init_face_recognition(API_KEY)CompreFace.init_face_detection(api_key)Inits face detection service object.ArgumentTypeRequiredNotesapi_keystringrequiredFace Detection Api Key in UUID formatExample:fromcompreface.serviceimportDetectionServiceDETECTION_API_KEY:str='your_face_detection_key'detection:DetectionService=compre_face.init_face_detection(DETECTION_API_KEY)CompreFace.init_face_verification(api_key)Inits face verification service object.ArgumentTypeRequiredNotesapi_keystringrequiredFace Verification Api Key in UUID formatExample:fromcompreface.serviceimportVerificationServiceVERIFICATION_API_KEY:str='your_face_verification_key'verify:VerificationService=compre_face.init_face_verification(VERIFICATION_API_KEY)Options structureOptions is optional field in every request that contains an image.
If the option’s value is set in the global object and passed as a function argument then the function argument value will be used.classDetProbOptionsDict(TypedDict):det_prob_threshold:floatclassExpandedOptionsDict(DetProbOptionsDict):limit:intstatus:boolface_plugins:strclassAllOptionsDict(ExpandedOptionsDict):prediction_count:intOptionTypeNotesdet_prob_thresholdstringminimum required confidence that a recognized face is actually a face. Value is between 0.0 and 1.0limitintegermaximum number of faces on the image to be recognized. It recognizes the biggest faces first. Value of 0 represents no limit. Default value: 0prediction_countintegermaximum number of subject predictions per face. It returns the most similar subjects. Default value: 1face_pluginsstringcomma-separated slugs of face plugins. If empty, no additional information is returned.Learn morestatusbooleanif true includes system information like execution_time and plugin_version fields. Default value is falseExample of face recognition with object:recognition.recognize(image_path=image_path,options={"limit":0,"det_prob_threshold":0.8,"prediction_count":1,"face_plugins":"calculator,age,gender,landmarks","status":"true"})Face Recognition ServiceFace recognition service is used for face identification.
This means that you first need to upload known faces to face collection and then recognize unknown faces among them.
When you upload an unknown face, the service returns the most similar faces to it.
Also, face recognition service supports verify endpoint to check if this person from face collection is the correct one.
For more information, seeCompreFace page.Recognize Faces from a Given ImageExampleRecognizes all faces from the image.
The first argument is the image location, it can be an url, local path or bytes.recognition.recognize(image_path,options)ArgumentTypeRequiredNotesimage_pathimagerequiredImage can pass from url, local path or bytes. Max size is 5MboptionsobjectoptionalAllOptionsDictobject can be used in this method. See morehere.Response:{"result":[{"age":{"probability":0.9308982491493225,"high":32,"low":25},"gender":{"probability":0.9898611307144165,"value":"female"},"mask":{"probability":0.9999470710754395,"value":"without_mask"},"embedding":[9.424854069948196E-4,"...",-0.011415496468544006],"box":{"probability":1.0,"x_max":1420,"y_max":1368,"x_min":548,"y_min":295},"landmarks":[[814,713],[1104,829],[832,937],[704,1030],[1017,1133]],"subjects":[{"similarity":0.97858,"subject":"subject1"}],"execution_time":{"age":28.0,"gender":26.0,"detector":117.0,"calculator":45.0,"mask":36.0}}],"plugins_versions":{"age":"agegender.AgeDetector","gender":"agegender.GenderDetector","detector":"facenet.FaceDetector","calculator":"facenet.Calculator","mask":"facemask.MaskDetector"}}ElementTypeDescriptionageobjectdetected age range. Return only ifage pluginis enabledgenderobjectdetected gender. Return only ifgender pluginis enabledmaskobjectdetected mask. Return only ifface mask pluginis enabled.embeddingarrayface embeddings. Return only ifcalculator pluginis enabledboxobjectlist of parameters of the bounding box for this faceprobabilityfloatprobability that a found face is actually a facex_max, y_max, x_min, y_minintegercoordinates of the frame containing the facelandmarksarraylist of the coordinates of the frame containing the face-landmarks.subjectslistlist of similar subjects with size of <prediction_count> order by similaritysimilarityfloatsimilarity that on that image predicted personsubjectstringname of the subject in Face Collectionexecution_timeobjectexecution time of all pluginsplugins_versionsobjectcontains information about plugin versionsGet Face Collectionrecognition.get_face_collection()Returns Face collection objectFace collection could be used to manage known faces, e.g. add, list, or delete them.Face recognition is performed for the saved known faces in face collection, so before using therecognizemethod you need to save at least one face into the face collection.More information about face collection and managing exampleshereMethods:Add an Example of a SubjectExampleThis creates an example of the subject by saving images. You can add as many images as you want to train the system. Image should
contain only one face.face_collection.add(image_path,subject,options)ArgumentTypeRequiredNotesimage_pathimagerequiredImage can pass from url, local path or bytes. Max size is 5Mbsubjectstringrequiredis the name you assign to the image you saveoptionsobjectoptionalDetProbOptionsDictobject can be used in this method. See morehere.Response:{"image_id":"6b135f5b-a365-4522-b1f1-4c9ac2dd0728","subject":"subject1"}ElementTypeDescriptionimage_idUUIDUUID of uploaded imagesubjectstringSubject of the saved imageList of All Saved Examples of the SubjectTo retrieve a list of subjects saved in a Face Collection:face_collection.list()Response:{
  "faces": [
    {
      "image_id": <image_id>,
      "subject": <subject>
    },
    ...
  ]
}ElementTypeDescriptionimage_idUUIDUUID of the facesubjectstringof the person, whose picture was saved for this api keyDelete All Examples of the Subject by NameExampleTo delete all image examples of the :face_collection.delete_all(subject)ArgumentTypeRequiredNotessubjectstringoptionalis the name you assign to the image you save. If this parameter is absent, all faces in Face Collection will be removedResponse:{
    "deleted": <count>
}ElementTypeDescriptiondeletedintegerNumber of deleted facesDelete an Example of the Subject by IDExampleTo delete an image by ID:face_collection.delete(image_id)ArgumentTypeRequiredNotesimage_idUUIDrequiredUUID of the removing faceResponse:{
  "image_id": <image_id>,
  "subject": <subject>
}ElementTypeDescriptionimage_idUUIDUUID of the removed facesubjectstringof the person, whose picture was saved for this api keyVerify Faces from a Given ImageExampleface_collection.verify(image_path,image_id,options)Compares similarities of given image with image from your face collection.ArgumentTypeRequiredNotesimage_pathimagerequiredImage can pass from url, local path or bytes. Max size is 5Mbimage_idUUIDrequiredUUID of the verifying faceoptionsstringObjectExpandedOptionsDictobject can be used in this method. See morehere.Response:{"result":[{"age":{"probability":0.9308982491493225,"high":32,"low":25},"gender":{"probability":0.9898611307144165,"value":"female"},"mask":{"probability":0.9999470710754395,"value":"without_mask"},"embedding":[9.424854069948196E-4,"...",-0.011415496468544006],"box":{"probability":1.0,"x_max":1420,"y_max":1368,"x_min":548,"y_min":295},"landmarks":[[814,713],[1104,829],[832,937],[704,1030],[1017,1133]],"subjects":[{"similarity":0.97858,"subject":"subject1"}],"execution_time":{"age":28.0,"gender":26.0,"detector":117.0,"calculator":45.0,"mask":36.0}}],"plugins_versions":{"age":"agegender.AgeDetector","gender":"agegender.GenderDetector","detector":"facenet.FaceDetector","calculator":"facenet.Calculator","mask":"facemask.MaskDetector"}}ElementTypeDescriptionageobjectdetected age range. Return only ifage pluginis enabledgenderobjectdetected gender. Return only ifgender pluginis enabledmaskobjectdetected mask. Return only ifface mask pluginis enabled.embeddingarrayface embeddings. Return only ifcalculator pluginis enabledboxobjectlist of parameters of the bounding box for this faceprobabilityfloatprobability that a found face is actually a facex_max, y_max, x_min, y_minintegercoordinates of the frame containing the facelandmarksarraylist of the coordinates of the frame containing the face-landmarks. Return only iflandmarks pluginis enabledsimilarityfloatsimilarity that on that image predicted personexecution_timeobjectexecution time of all pluginsplugins_versionsobjectcontains information about plugin versionsGet Subjectsrecognition.get_subjects()Returns subjects objectSubjects object allows working with subjects directly (not via subject examples).More information about subjectshereMethods:Add a SubjectExampleCreate a new subject in Face Collection.subjects.add(subject)ArgumentTypeRequiredNotessubjectstringrequiredis the name of the subject. It can be any stringResponse:{"subject":"subject1"}ElementTypeDescriptionsubjectstringis the name of the subjectList SubjectsExampleReturns all subject related to Face Collection.subjects.list()Response:{"subjects":["<subject_name1>","<subject_name2>"]}ElementTypeDescriptionsubjectsarraythe list of subjects in Face CollectionRename a SubjectExampleRename existing subject. If a new subject name already exists, subjects are merged - all faces from the old subject name are reassigned to the subject with the new name, old subject removed.subjects.rename(subject,new_name)ArgumentTypeRequiredNotessubjectstringrequiredis the name of the subject that will be updatednew_namestringrequiredis the name of the subject. It can be any stringResponse:{"updated":"true|false"}ElementTypeDescriptionupdatedbooleanfailed or successDelete a SubjectExampleDelete existing subject and all saved faces.subjects.delete(subject)ArgumentTypeRequiredNotessubjectstringrequiredis the name of the subject.Response:{"subject":"subject1"}ElementTypeDescriptionsubjectstringis the name of the subjectDelete All SubjectsExampleDelete all existing subjects and all saved faces.subjects.delete_all()Response:{"deleted":"<count>"}ElementTypeDescriptiondeletedintegernumber of deleted subjectsFace Detection ServiceFace detection service is used for detecting faces in the image.Methods:DetectExampledetection.detect(image_path,options)Finds all faces on the image.ArgumentTypeRequiredNotesimage_pathimagerequiredimage where to detect faces. Image can pass from url, local path or bytes. Max size is 5MboptionsstringObjectExpandedOptionsDictobject can be used in this method. See morehere.Response:{"result":[{"age":{"probability":0.9308982491493225,"high":32,"low":25},"gender":{"probability":0.9898611307144165,"value":"female"},"mask":{"probability":0.9999470710754395,"value":"without_mask"},"embedding":[-0.03027934394776821,"...",-0.05117142200469971],"box":{"probability":0.9987509250640869,"x_max":376,"y_max":479,"x_min":68,"y_min":77},"landmarks":[[156,245],[277,253],[202,311],[148,358],[274,365]],"execution_time":{"age":30.0,"gender":26.0,"detector":130.0,"calculator":49.0,"mask":36.0}}],"plugins_versions":{"age":"agegender.AgeDetector","gender":"agegender.GenderDetector","detector":"facenet.FaceDetector","calculator":"facenet.Calculator","mask":"facemask.MaskDetector"}}ElementTypeDescriptionageobjectdetected age range. Return only ifage pluginis enabledgenderobjectdetected gender. Return only ifgender pluginis enabledmaskobjectdetected mask. Return only ifface mask pluginis enabled.embeddingarrayface embeddings. Return only ifcalculator pluginis enabledboxobjectlist of parameters of the bounding box for this face (on processedImage)probabilityfloatprobability that a found face is actually a face (on processedImage)x_max, y_max, x_min, y_minintegercoordinates of the frame containing the face (on processedImage)landmarksarraylist of the coordinates of the frame containing the face-landmarks. Return only iflandmarks pluginis enabledexecution_timeobjectexecution time of all pluginsplugins_versionsobjectcontains information about plugin versionsFace Verification ServiceExampleFace verification service is used for comparing two images.
A source image should contain only one face which will be compared to all faces on the target image.Methods:Verifyverify.verify(source_image_path,target_image_path,options)Compares two images provided in arguments. Source image should contain only one face, it will be compared to all faces in the target image.ArgumentTypeRequiredNotesimage_idUUIDrequiredUUID of the verifying facesource_image_pathimagerequiredfile to be verified. Image can pass from url, local path or bytes. Max size is 5Mbtarget_image_pathimagerequiredreference file to check the source file. Image can pass from url, local path or bytes. Max size is 5MboptionsstringObjectExpandedOptionsDictobject can be used in this method. See morehere.Response:{"result":[{"source_image_face":{"age":{"probability":0.9308982491493225,"high":32,"low":25},"gender":{"probability":0.9898611307144165,"value":"female"},"mask":{"probability":0.9999470710754395,"value":"without_mask"},"embedding":[-0.0010271212086081505,"...",-0.008746841922402382],"box":{"probability":0.9997453093528748,"x_max":205,"y_max":167,"x_min":48,"y_min":0},"landmarks":[[92,44],[130,68],[71,76],[60,104],[95,125]],"execution_time":{"age":85.0,"gender":51.0,"detector":67.0,"calculator":116.0,"mask":36.0}},"face_matches":[{"age":{"probability":0.9308982491493225,"high":32,"low":25},"gender":{"probability":0.9898611307144165,"value":"female"},"mask":{"probability":0.9999470710754395,"value":"without_mask"},"embedding":[-0.049007344990968704,"...",-0.01753818802535534],"box":{"probability":0.99975,"x_max":308,"y_max":180,"x_min":235,"y_min":98},"landmarks":[[260,129],[273,127],[258,136],[257,150],[269,148]],"similarity":0.97858,"execution_time":{"age":59.0,"gender":30.0,"detector":177.0,"calculator":70.0,"mask":36.0}}],"plugins_versions":{"age":"agegender.AgeDetector","gender":"agegender.GenderDetector","detector":"facenet.FaceDetector","calculator":"facenet.Calculator","mask":"facemask.MaskDetector"}}]}ElementTypeDescriptionsource_image_faceobjectadditional info about source image faceface_matchesarrayresult of face verificationageobjectdetected age range. Return only ifage pluginis enabledgenderobjectdetected gender. Return only ifgender pluginis enabledmaskobjectdetected mask. Return only ifface mask pluginis enabled.embeddingarrayface embeddings. Return only ifcalculator pluginis enabledboxobjectlist of parameters of the bounding box for this faceprobabilityfloatprobability that a found face is actually a facex_max, y_max, x_min, y_minintegercoordinates of the frame containing the facelandmarksarraylist of the coordinates of the frame containing the face-landmarks. Return only iflandmarks pluginis enabledsimilarityfloatsimilarity between this face and the face on the source imageexecution_timeobjectexecution time of all pluginsplugins_versionsobjectcontains information about plugin versionsContributingContributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are greatly appreciated.Fork the ProjectCreate your Feature Branch (git checkout -b feature/AmazingFeature)Commit your Changes (git commit -m 'Add some AmazingFeature')Push to the Branch (git push origin feature/AmazingFeature)Open a Pull RequestAfter creating your first contributing pull request, you will receive a request to sign our Contributor License Agreement by commenting your pull request with a special message.Report BugsPlease report any bugshere.If you are reporting a bug, please specify:Your operating system name and versionAny details about your local setup that might be helpful in troubleshootingDetailed steps to reproduce the bugSubmit FeedbackThe best way to send us feedback is to file an issue athttps://github.com/exadel-inc/compreface-python-sdk/issues.If you are proposing a feature, please:Explain in detail how it should work.Keep the scope as narrow as possible to make it easier to implement.License infoCompreFace Python SDK is open-source facial recognition SDK released under theApache 2.0 license.