Saravanan666/pypi-org huggingface dataset:
Package: facemask-detection
Facemask detectionIt could be confusing, but the model in this library perform classifications of the images.
It takes image as an input and outputs probability of person in the image wearing a mask.Hence in order to get expected results the model should be combined with face detector, for example fromhttps://github.com/ternaus/retinaface.Example on how to combine face detector with mask detectorInstallationpip install -U facemask_detectionUseimportalbumentationsasAimporttorchfromfacemask_detection.pre_trained_modelsimportget_modelmodel=get_model("tf_efficientnet_b0_ns_2020-07-29")model.eval()transform=A.Compose([A.SmallestMaxSize(max_size=256,p=1),A.CenterCrop(height=224,width=224,p=1),A.Normalize(p=1)])image = <numpy array with the shape (height, width, 3)>transformed_image=transform(image=image)['image']input=torch.from_numpy(np.transpose(transformed_image,(2,0,1))).unsqueeze(0)print("Probability of the mask on the face = ",model(input)[0].item())Jupyter notebook with the example:Jupyter notebook with the example on how to combine face detector with mask detector:Train setTrain dataset was composed from the data:No mask:VGGFace2Mask:https://www.kaggle.com/andrewmvd/face-mask-detectionhttps://www.kaggle.com/alexandralorenzo/maskdetectionhttps://github.com/X-zhangyang/Real-World-Masked-Face-Datasethttps://humansintheloop.org/medical-mask-datasetTraininingDefine config, similar tofacemask_detection_configs/2020-07-29.yaml.Runpythonfacemask_detection/train.py-c<config>Inferencepython-mtorch.distributed.launch--nproc_per_node=1facemask_detection/inference.py-h
usage:inference.py[-h]-iINPUT_PATH-cCONFIG_PATH-oOUTPUT_PATH[-bBATCH_SIZE][-jNUM_WORKERS]-wWEIGHT_PATH[--world_sizeWORLD_SIZE][--local_rankLOCAL_RANK][--fp16]optionalarguments:-h,--helpshowthishelpmessageandexit-iINPUT_PATH,--input_pathINPUT_PATHPathwithimages.-cCONFIG_PATH,--config_pathCONFIG_PATHPathtoconfig.-oOUTPUT_PATH,--output_pathOUTPUT_PATHPathtosavejsons.-bBATCH_SIZE,--batch_sizeBATCH_SIZEbatch_size-jNUM_WORKERS,--num_workersNUM_WORKERSnum_workers-wWEIGHT_PATH,--weight_pathWEIGHT_PATHPathtoweights.--world_sizeWORLD_SIZEnumberofnodesfordistributedtraining--local_rankLOCAL_RANKnoderankfordistributedtraining--fp16Usefp6Example:python -m torch.distributed.launch --nproc_per_node=<num_gpu> facemask_detection/inference.py \
                                   -i <input_path> \
                                   -w <path to weights> \
                                   -o <path to the output_csv> \
                                   -c <path to config>
                                   -b <batch size>
Package: face-mask-detector
face-mask-detectorA library and command line utility for detecting face masks in images and video streamsInstallAs always, the use of a pythonvirtual
environmentis recommended for a
development setup:python-mvenvvenvsourcevenv/bin/activateTo install usingpip:pipinstallface-mask-detectorQuick StartTo detect face masks in a image, run:face-mask-detector--imagepath/to/imageTo start your webcam and detect face masks in the video stream, run:face-mask-detectorContributeI :heart: pull requests and defect reports - I welcome contributions of any kind!To installface-mask-detectorfrom source, clone this repository and run the
following in the project root directory:pipinstall-e'.[dev]'
Package: facematch
FacematchFacematch is a tool to verifies if two photos contain the same person.input1input2outputresult{"match": true, "distance": 0.38913072553055295}{"match": true, "distance": 0.5131670729305189}{"match": true, "distance": 0.4370069082351905}{"match": false, "distance": 0.7838337220196059}{"match": false, "distance": 0.8705370438394476}InstallationInstall it from pypipipinstallfacematchUsage as a cliWithout output imagefacematchinput1.pnginput2.pngWith output imagefacematch-ooutput.pnginput1.pnginput2.pngUsage as a libraryInapp.pyfromfacematch.faceimportmatchf=open('img1.png','rb')data1=f.read()f.close()f=open('img2.png','rb')data2=f.read()f.close()result,distance,data=match(data1,data2)f=open('out.png','wb')f.write(data)f.close()print(distance)print(result)Then runpython app.pyLicenseCopyright (c) 2020-presentDaniel GatisLicensed underMIT License
Package: faceMongo
faceMongoScrape facebook public page and save it  in a mongo database as a collection of documents.
Retrieve a collection from mongo database.InstallattionRun the following command in your terminal to install the packagepip install faceMongoUsageScraping facebook public pageUsingdonaldtrumpand saviing it in a mongo database namedfacebook.  Assuming you have a mongo database
installed locally.The following code will retrive and save the document in your mongo databasefrom faceMongo import faceMongo

fm = faceMongo.FaceMongo('facebook','localhost',27017) # database, host and port
fm.fb_page_to_db('donaldtrump') # scrape donaldtrump page to databaseRetrieving collection from the mongo databaseTo retrivedonaldtrumpcollection from the facebook database,
The code below will return the collection of documents in a listdocs = fm.docs_from_db('donaldtrump' )LicenceMIT License
Package: facemosaic
facemosaic模块介绍安装方法使用方法使用实例相关网址模块介绍该模块可以在脱机状态下识别人脸并加上马赛克。该模块目前采用的深度学习框架为'caffe'。该模块需要依赖opencv-python。暂不支持cuda加速。安装方法在cmd窗口下输入:pip install facemosaic使用方法函数：add_mosaic该函数用于识别图片中的人脸并加上马赛克必要参数:img 可选参数:pixel_width conf_threshold对于可选参数的说明请见下文
返回：会返回修改后的图像，使用cv2的imwrite函数即可保存图像get_face识别图片中的人脸位置
必要参数:img 可选参数:conf_thresholdimg -> 通过cv2中imread函数返回的值flags使用默认参数conf_threshold -> 要求参数为不大于1不小于0的浮点数。该参数可规定识别的人脸形态阈值(建议不小于0.6)返回：会返回一个列表 -> [[人脸左下角横坐标, 人脸左下角纵坐标, 人脸宽度, 人脸高度], ...]（原点位于图片左下角）mosaic该函数用于为图片加上马赛克必要参数:img facial_position 可选参数:pixel_widthimg -> 通过cv2中imread函数返回的值flags使用默认参数facial_position -> 需要get_face函数的返回值
pixel_width -> 关于定义像素化部分一个色块的宽度(单位为像素)
返回：会返回修改后的图像，使用cv2的imwrite函数即可保存图像使用实例批量图像打码importos# 获取图片路径importcv2# 用于读写图片importfacemosaic# 用于打码的模块importtime# 用于计算代码运算时间read_path='./images/'# 原图片的文件夹save_path='./save/'#  打码后的图片文件夹st=time.time()# 开始时间forfile_namesinos.walk(read_path):forfile_nameinfile_names[2]:# 获取图片文件名data=facemosaic.add_mosaic(cv2.imread(read_path+file_name))# 获取加工后的图片cv2.imwrite(save_path+os.path.splitext(file_name)[0]+'.png',data)# 保存图片et=time.time()# 结束时间print(f'ok.it uses{et-st}s')# 输出总用时实时人脸打码importcv2# 读取摄像头内容，保存视频importfacemosaic# 用于打码的模块cap=cv2.VideoCapture(0)# 打开摄像头vw=int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))# 获取摄像头宽vh=int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))# 获取摄像头高fps=cap.get(cv2.CAP_PROP_FPS)# 获取视频帧率（最好根据实际每秒加工的图像数量设置否则视频会被加速或减速）video=cv2.VideoWriter('./save_cv.mp4',cv2.VideoWriter_fourcc('m','p','4','v'),fps,(vw,vh))# 将打码后的内容保存为视频whileTrue:ret,frame=cap.read()# 读取图片data=facemosaic.add_mosaic(frame)# 对图像进行加工cv2.imshow("video",data)# 显示打码后的图像video.write(data)# 写入数据ifcv2.waitKey(1)&0xFF==ord('q'):# 按q退出breakcap.release()# 释放资源cv2.destroyAllWindows()# 关闭所有窗口对视频中人脸打码importfacemosaicimporttimeimportcv2st=time.time()# 获取开始时间cap=cv2.VideoCapture('./test_v.mp4')# 打开原视频vw=int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))# 获取原视频宽vh=int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))# 获取原视频高fps=cap.get(cv2.CAP_PROP_FPS)# 获取原视频帧率video=cv2.VideoWriter('./save_v.mp4',cv2.VideoWriter_fourcc('m','p','4','v'),fps,(vw,vh))# 保存加工后的视频whileTrue:ret,frame=cap.read()# 读取一帧ifnot(ret):# 当没有可以读取的数据后结束循环breakvideo.write(facemosaic.add_mosaic(frame,pixel_width=25))# 保存加工后的帧cap.release()# 释放资源et=time.time()# 结束时间print(f'ok.it uses{et-st}s')# 输出总运行时间相关网址帮助文档
Package: facenet-face-recognition
Face RecognitionSimple library to recognize faces from given imagesFace Recognition pipelineBelow the pipeline for face recognition:Face Detection: theMTCNNalgorithm is used to do face detectionFace AlignementAlign face by eyes lineFace EncodingExtract encoding from face usingFaceNetFace ClassificationClassify face via eculidean distrances between face encodingsHow to installpip install git+https://github.com/paoloripamonti/face-recognitionHow to train custom modelInitialize modelfromface_recognitionimportFaceRecognitionfr=FaceRecognition()Train model with pandas DataFrame:fr=FaceRecognition()fr.fit_from_dataframe(df)where 'df' is pandas DataFrame with columnperson(person name) and columnpath(image path)Train model with folder:fr=FaceRecognition()fr.fit('/path/root/')the root folder must have the following structure:root\
    Person_1\
        image.jpg
        ...
        image.jpg
    Person_2\
        image.jpg
        ...
        image.jpg
    ...Save and load modelyou can save and load model aspicklefile.fr.save('model.pkl')fr=FaceRecognition()fr.load('model.pkl')Predict imagefr.predict('/path/image.jpg')Recognize faces from given image.
The output is a JSON with folling structure:{
  "frame": "image data", # base64 image with bounding boxes
  "elapsed_time": time, # elapsed time in seconds
  "predictions": [
      {
        "person": "Person", # person name
        "confidence": float, # prediction confidence
        "box": (x1, y1, x2, y2) # face bounding box
      }
  ]
}ExampleFor more details you can see:https://www.kaggle.com/paoloripamonti/face-recogniton
Package: facenet-khairulimam
ResFacenetThis package is intended as anpytorch hubentry point for my trained facenet model on this repokhrlimam/facenet.
This pretrained model can be used for anyone who want to use it for transfer learning or any other applications.This model trained on VGGv2 dataset and tested on LFW dataset and gained 92% accuracy.This work is distributed under MIT license, so I hope you consider the license's policy. Cheers!
Package: facenet-opencv
facenet-opencvFaceNet face features using OpenCVCreditsfacenetbydavidsandbergfacenet_opencv_dnnbyTanFluentWhy this existsThe original project need tensorflow installed.The method/model need tensorflow 1.x, which is unavailable on python 3.8.A package with model in it, without depending tensorflow, is convenient.How is this doneDownload original models20180408-102900Or20180402-114759Install Tensorflow environmentpython3.6 on linuxpip3 install protobuf==3.19.4 grpcio==1.8.6 tensorflow==1.7Run the scriptswith some model path fixpython3 convert_variable_to_constant.pypython3 convert_tf_pb_to_cv_pb.pyBe noticed: the package contains the result of model20180408-102900.How to useInstallpip3installopencv-python
pip3installmtcnn_opencv
pip3installfacenet_opencvCodefromfacenet_cv2importFaceNetmodel=FaceNet()vectors=model.face_features(open("x.jpg","rb").read())forvinvectors:print(v)
Package: face-network
face-networkCreate a social network graph based on coappearance in images. Given a large volume of images of people this tool:Extracts facesClusters faces based on similarityCreates a social network graph based on co-appearance in imagesThe three steps above correspond to the black arrows on the left of the diagram below:1. Extracting facesface_network.extract_faces(source_dir,age_gender=False)This function extracts all faces from a directory of images using Dlib’s face detector, and must be run prior to further analysis.Outputs:This function creates a new folder called “Face Network” in your image directory. When a face is identified, it is cropped and stored in a new folder “source_dir/Face Network/Faces/”. Given “Image.jpg” containing two faces, this function will save two cropped faces: “face1_Image.jpg” and “face2_Image.jpg”. Facial encodings (128-dimensional vectors used for clustering and matching similar faces) are stored in a file called “FaceDatabase.h5”.2. Clustering Facesface_network.cluster(source_dir,algorithm='DBSCAN',iterations=1,initial_eps=0.45,max_distance=45)Once faces are extracted, similar faces are clustered together. This function uses a density-based clustering algorithm (DBSCAN) to identify clusters of similar faces in the list of facial encodings. Starting with loose clustering parameters, the function iteratively decreases the neighborhood distance parameter. In each iteration, facial similarity within clusters is evaluated. Dense clusters are extracted, and sparse clusters are assigned to be re-evaluated in the next iteration. When an iteration returns no new clusters, the function returns a dataframe containing facial encodings grouped into clusters based on similarity.Outputs:Rows in the FaceDatabase.h5 file now contain a unique numeric identifier, grouping similar faces into clusters. If the “mosaic” option is enabled, an image composed of all of the face tiles in a given cluster is created:3. Generating a Networkface_network.network(photo_dir,scale=10)Having identified individuals across multiple pictures, this function generates a force directed graph based on co-appearance in images. Each individual is a node, and each co-appearance is an edge.Output:A file called “Image_Network.html” is created in "photo_directory/Face Network/Data/".The graph can be opened in a web browser and is fully interactive. Hovering over a node will display a tooltip showing the cluster’s unique identifier. This corresponds to the filenames of the mosaics generated in the previous step:Example ProjectGiven a folder called “photo_dir” with five images, the following process extracts faces, clusters similar faces, and creates a co-appearance network:importface_networkphoto_dir="Users/oballinger/Downloads/photo_dir"face_network.extract(photo_dir,age_gender=True)face_network.cluster(photo_dir,algorithm='DBSCAN',iterations=10,initial_eps=0.44,max_distance=40)face_network.network(photo_dir,size=20)The diagram below shows the file structure of the resulting outputs:
Package: face-picture-comparator
face_picture_comparatorDescription.The package face_picture_comparator is used to:- Delimit face
- Confront faces
- Confront faces message
- Plot image
- Plot result
- Get image fileInstallationUse the package managerpipto install face_picture_comparatorpipinstallface_picture_comparatorUsagefromface_picture_comparatorimportload_imgimage=load_img.get_image_file("my_image.jpg")image=load_img.delimit_face(image)# delimit_face returns an image with a rectangle delimiting the first face detected in the input image# the image containing the contour of the face should not be used as input to face comparison methods# (confront_faces_message and confront_faces)fromface_picture_comparatorimportload_imgfromface_picture_comparatorimportcomparationfromface_picture_comparatorimportplotimage=load_img.get_image_file("my_image.jpg")image_compare=load_img.get_image_file("other_image.jpg")message_result=comparation.confront_faces_message(image,image_compare)# result_confront_faces returns a string informing whether or not the faces belong to the same person and the distance between themcomparison_result=comparation.confront_faces(image,image_compare)# returns a tuple where the first value is a boolean, which says whether or not the faces belong to the same person, and the second# value is a float that represents the distance between the facesplot.plot_result(image,image_compare,message_result)# plot_result displays the images and the massage using matplotlib libraryfromface_picture_comparatorimportload_imgfromface_picture_comparatorimportplotimage=load_img.get_image_file("my_image.jpg")plot.plot_image(image)# plot_image displays the image using matplotlib libraryAuthorRonaldo NunesLicenseMIT
Package: facepixellate
facepixellateDetect and pixellate faces in the picture, with varying pixel sizeEnvironmentpython 3.6
opencvInstallationpip install facepixellateUsage1. Inside python code -Sample codeimport facepixellate 
import cv2 

img_p = facepixellate.pixellate_face("test_face.jpg", 0)
cv2.imwrite("output.jpg",img_p)P.S :Check homepage ( github ) for detailed description
Package: face-pose
Infoface_pose.py 2018-05-25Author: Zhao Mingming <471106585@qq.com>Copyright: This module has been placed in the public domain.version:0.0.1-add get_image_poseFunctions:face_pose: get face poseHow To Use This Moduleexample code:imagepath="closed_eye/9.jfif"img=io.imread(imagepath)img1=imgimagepath="closed_eye/14.jfif"img2=io.imread(imagepath)ldmer=ldm.LDM()printimg.shape[0]ldl,facel,txt=ldmer.landmarks(img)printtxtforldinldl:print10*'-'print'nose:'printld['nose']forfaceinfacel:print10*'-'print'face:'printface.top()printface.left()printface.width()printface.height()printface.bottom()printface.right()x,y,w,h=[face.top(),face.left(),face.width(),face.height()]printx,y,w,hprint"feature:"ffl=ldmer.face_feature(img,facel)forffinffl:printhelp(ff)print'ff='+str(ff)print'len(ff)='+str(len(ff))print'ff[0]='+str(ff[0])print'ff[127]='+str(ff[127])print"face compare:"printldmer.face_rec(img1,img2)printldmer.has_same_person(img1,img2)printldmer.has_same_person(img2,img2)print"face number:"printldmer.face_number(img,facel)Refreshadd a function : ldmer.imread(imgpath)
modify  the return value number to: has_flag,max_score=ldmer.has_same_person(img1,img2)
Package: face_processor
face-processorTool to process faces for psychophysics experiments.Adjust position of faces
make the images equiluminantTODO: Describe moduleBainbridge, W. A., Isola, P., & Oliva, A. (2013). The Intrinsic Memorability of Face Photographs. Journal of Experimental Psychology: General, 142(4), 1323 - 1334.usageprocess distractorsThis is done once to generate our distractor/control faces from the Bainsbridge database:python process_distractors.pyprocess probePlace original photos instimuli/original/probes. Crop the photo to leave a small margin around the top of the head, the ears and then chin. Then run (e.g.,):python process_probe.py ../original/probes/001.jpeg 1 M
Package: face-projection
face-projectionAre you looking for a powerful, user-friendly tool to project information onto faces while maintaining their natural structure?
Look no further –face-projectionis here to simplify how you visualize facial data.
The tool is open-source, easy to use, and written in Python, allowing you to easily integrate it into your existing workflow.
We try to keep the dependencies to a minimum so you can use them in your projects without worrying about compatibility issues.
However, we do not guarantee perfect anatomical correctness of the results but try to keep the distortion to a minimum.All people shown here in the repository examples were generated withStableDiffusion(Prompt:A professional portrait photo of a person directly looking <emotion> at the camera, white background, photoshop, Instagram)InstallationThe tool is available onPyPI.pipinstallface-projectionUsageThe tool reduces the overhead of projecting information onto faces to a minimum.
Load the data and face, project it, and you are done.
You must only ensure the data is inside the canonical face model (seeelectromyogramfor an example).
The head pose can be arbitrary, but the face must be visible.importface_projectionasfpfromPILimportImageimage_face=np.asarray(Image.open("face.jpg").convert("RGB"))image_data=np.asarray(Image.open("data.jpg").convert("RGB"))warper=fp.Warper()warped=warper.apply(image_face,image_data,beta=0.2)We automatically detect the face in the image, compute the landmarks based on theBlazemodel, and warp the data onto it.
You can decide how much of the underlying face should be visible by adjusting thebetaparameter.Inexamples/you can find a more detailed example, which generates the teaser image.Future WorkWe have many ideas for future work, but we are also happy to hear your suggestions.
The following todos are in no particular order but should give you an idea of what we are planning.The user can provide a mask to turn off certain parts of the projectionDifferent default warpings based on the six default Ekman emotionsMore face modelsCustom face modelsUpgrade to the newest mediapipe version to avoid MacOS build issuesCitationIf you use our work, please cite our paper:under publication, so coming soon :^)
Package: facepy
UsagefromfacepyimportGraphAPI# Initialize the Graph API with a valid access token (optional,# but will allow you to do all sorts of fun stuff).graph=GraphAPI(oauth_access_token)# Get my latest postsgraph.get('me/posts')# Post a photo of a parrotgraph.post(path='me/photos',source=open('parrot.jpg','rb'))Facepy can do more than reading your latest posts and posting photographs of parrots, but you’ll have toread the documentationto find out how.Please note that Facepy doesnotdo authentication with Facebook; it only consumes its API. To get an
access token to consume the API on behalf of a user, use a suitable OAuth library for your platform (if you’re
using Django, for example, you might useFandjango).Installation$pipinstallfacepyContributeForkthe repository.Do your thing (preferably on a feature branch).Write a test that demonstrates that the bug was fixed or the feature works as expected.Send a pull request and bug me until I merge it!I love youJohannes Gorset made this. You shouldtweet meif you can’t get it
to work. In fact, you should tweet me anyway.I love SchibstedI work atSchibsted Products & Technologywith a bunch of awesome folks
who are every bit as passionate about building things as I am. If you’re using
Facepy, we probably want to hire you.
Package: face-recognition-ai
Face-Recognition-AIWelcome to Face-Recognition-AI, an advanced face recognition system built with cutting-edge technologies, including FaceNet and YOLO5Face. This project draws inspiration from the popular face-recognition module, aiming to provide users with a professional and efficient solution for face recognition.🚀 Getting StartedTo get started with Face-Recognition-AI, follow these simple steps:pip install face-recognition-aiRun python usage.pyfrom PIL import Image

from face_recognition_ai import match_faces, show_detections

unknown_with_multiple_faces = Image.open("images/multi.jpeg")

known = Image.open("images/sakib.jpg")
known_person_name = "sakib"

print(True if True in match_faces(unknown_with_multiple_faces, known) else False)
img = show_detections(unknown_with_multiple_faces, known, known_person_name)
img.show()💡 FeaturesFaceNet Integration: Leveraging the power of FaceNet, our system directly learns a mapping from face images to a compact Euclidean space, enabling accurate and efficient face recognition [5].YOLO5Face Detection: The YOLO5Face model enhances face detection capabilities, ensuring robust identification of faces in various scenarios.Inspired by Face-Recognition Module: We take inspiration from the widely-used face-recognition module, incorporating best practices and user-friendly design.🤝 Contribution GuidelinesWe welcome contributions to make Face-Recognition-AI even more professional. If you'd like to contribute, please follow these guidelines:Fork the repository.Create a new branch:git checkout -b feature/your-feature.Make your changes and commit them:git commit -m 'Add your feature'.Push to the branch:git push origin feature/your-feature.Submit a pull request.📄 LicenseThis project is licensed under the MIT License - see the LICENSE file for details.🌐 SourcesGitHub - Awesome Face Detection and Recognition
GitHub - Face Recognition OpenCV Facenet
Medium - Face Recognition in Python| FaceNet, MTCNN and SVM
Towards Data Science - Using FaceNet For On-Device Face Recognition With Android
ArXiv - A Unified Embedding for Face Recognition and Clustering
Viso AI - DeepFace - Most Popular Deep Face Recognition in 2024
Package: face-recognition-and-drowsiness-detection
Face Recocognition & Drowsiness DetectionPython Boilerplate contains all the boilerplate you need to create a Python package.Free software: MIT licenseDocumentation:https://face-recognition-and-drowsiness-detection.readthedocs.io.FeaturesTODOCreditsThis package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.History0.1.0 (2021-05-03)First release on PyPI.