Solvedface_recognition Freeze your script with Pyinstaller

You might want to freeze your script into a standalone executable to run on any system without the need of installing python or face_recognition and maybe you want to create a demo for your application and want to give it to someone else without giving your source code. Here is a simple tutorial to do that. I tested this method with python3.6 on Windows 10, but I think you can get it working on Linux with a similar method.

  1. Make sure you have correctly installed both face_recognition and dlib and you see no error when importing them into your script.
  2. Make sure your script works fine, and all its dependencies are right next to it, and you can run it fine with python
  3. Install Pyinstaller with pip:
    pip install pyinstaller
  4. Create a new directory and move your python script and all dependencies into it. I call it myproject and
  5. Copy face_recognition_models and scipy-extra-dll from your python installed directory to your project directory.
  6. Create an empty file called <yourscriptname>.spec like myscript.spec next to your python script.
  7. Use below Pyinstaller spec file sample and edit some parts according to your needs: (I mark it with <> tag)
# -*- mode: python -*-

block_cipher = None

face_models = [
('.\\face_recognition_models\\models\\dlib_face_recognition_resnet_model_v1.dat', './face_recognition_models/models'),
('.\\face_recognition_models\\models\\mmod_human_face_detector.dat', './face_recognition_models/models'),
('.\\face_recognition_models\\models\\shape_predictor_5_face_landmarks.dat', './face_recognition_models/models'),
('.\\face_recognition_models\\models\\shape_predictor_68_face_landmarks.dat', './face_recognition_models/models'),

a = Analysis(['<your python script>'],
             pathex=['<path to working directory>'],
             hiddenimports=['scipy._lib.messagestream', 'scipy', 'scipy.signal', 'scipy.signal.bsplines', 'scipy.special', 'scipy.special._ufuncs_cxx',
                            'scipy.integrate._dop', 'scipy._lib', 'scipy._build_utils','scipy.__config__',
                            'scipy.integrate.lsoda', 'scipy.cluster', 'scipy.constants','scipy.fftpack','scipy.interpolate','','scipy.linalg','scipy.misc','scipy.ndimage','scipy.odr','scipy.optimize','scipy.setup','scipy.sparse','scipy.spatial','scipy.special','scipy.stats','scipy.version'],


a.datas += Tree('./scipy-extra-dll', prefix=None)

pyz = PYZ(a.pure, a.zipped_data,
exe = EXE(pyz,
          name='<your python script name>',
          console=True )
  1. Generate your executable with python -m pyinstaller myscript.spec
  2. If you see no error then your executable can be found in dist directory.
  3. Enjoy!

Thanks to @ageitgey and @davisking for their awesome work.

50 Answers

✔️Accepted Answer

@sincerefly Hi, If I remember correctly there are some examples that need scipy so if you are using scipy with your project you need those files but if you don't, just use face_models no need for hidden imports that is it. And remember you just need to first freeze your script normally and if you got any errors about missing packages, you need to feed them manually in your spec file.

Other Answers:

I found this worked very well when running on Windows desktop, but the application would crash on Windows Server 2012 - 2016 with an unhelpful, vague unable to execute DLL error. I found this issue was caused by using the latest version of dlib linked in the project install guide under issue 175 (currently 19.9.99). However, by using 'pip install dlib', which installs 19.9.0 (again, currently as of writing this). The frozen executable is running without errors on both desktop and server. I've also been testing freezing this in both 32-bit and 64-bit python and both are working. Thanks

Related Issues:

face_recognition How can I make face recognition faster if I have more than 1M known images?
The formula for euclidean distance is just: So assuming you had one column for each of the 128 featu...
face_recognition How to install face_recognition?
This was what i did Here I install face_recognition once to make sure all the dependencies is includ...
face_recognition IndexError: list index out of range
If no face is found in the image the encodings array will be empty So check the length of the array ...
react native camera Cannot choose between the following variants of project :react-native-camera:
@medicmilos @wimva @MeisterTea have you added the following to android/app/build.gradle?: Step 4 her...
react native camera Could not find method compileOnly()
Just went through this myself Which implementation are you using RNCamera Steps to reproduce init a ...
react native camera Could not resolve project :react-native-camera. on Android
For those who have this problem the solution that I found is setting classpath 3.3.0 and Gradle 4.10...
react native camera Failed to list versions for org.webkit:android-jsc.
Got the same issue with react-native-image-crop-picker fixed by maven { url }...
react native camera Could not find method google() for arguments [] on repository container
set set build.gradle Hi all I am having this error after i install react n...
react native camera "Could not resolve all dependencies for configuration ':app:_debugApkCopy'"
this worked for me while opening Android Studio to resolve the dependencies Which implementation are...
react native camera version conflict
change implementation project(':react-native-camera') to: Actual behaviour I am using this library t...
react native camera "camera not authorized" in version 1.8.0 (Android)
@adimshev Try to set the captureAudio property on the RNCamera component to false if you do not want...
react native camera Undefined is not an object(evaluating 'CameraManager.Aspect')
After installing and linking package important to rebuild native part of app. i try to make simple r...
facenet triplet training did not converged
Hi @davidsandberg I chose these parameters carefully and run a new experiment (20 days) The result i...
facenet error when running Validate_on_lfw
@farimani thank you~ I am new to the machine learning @davidsandberg I am trying to run the (Validat...
facenet Error loading a frozen graph ( float incompatible with float_ref )
my code I froze the 20170131-234652 model using the but I cannot load it in C++ I fi...
react native camera Preview photo and video after capturing
I am able to reproduce this issue with RNCamera however I'm not sure if this is RNCamera related ...
react native camera Could not find com.github.react-native-community:cameraview:df60b07573
react-native-camera@0.6.0 solved this problem but would crash the app if I tried to actually import ...
facenet pre-trained model unable to load because of tensorflow saver format :(
Hi I'm not sure which file you are trying to load I recently tried loading a pretrained model with t...
react native camera react-native-camera iOS is not detecting any faces
Hello GitHub this is my first time answering ever here :) Here's how I managed to make it work on iO...
react native camera Autolinking is not working on 0.61.1
I guess that the purpose of the autolinking is to avoid manual steps before using a lib in react-nat...
react native camera ios 10 - app crashes when view with <Camera> is rendered
In case anyone coming here isn't super familiar with xcode or Info.plist the two comments above are ...
react native camera Undefined is not an object (evaluating 'CameraManager.Aspect')
@patlux It worked for me to remove the previously-installed react-native-camera pod: and then manual...
react native camera Camera crashes on second capture (Android)
@ygorlf The idea is that you don't use the default goBack function but write your own ,which resets ...
opencv4nodejs fatal error: 'tesseract/baseapi.h' file not found
@GiulioPettenuzzo Let's say you receive output like this from your shell: The non-ideal ...
react native camera Pinch Zoom
the solution was provided by @cristianoccazinsp with the following answer Initial testing without us...
react native camera [Android] RNCamera crashes/freezes occasionally
I see a somehow similar problem on my side The loading spinner freezes (as well as the complete app)...
react native camera XCode build error Undefined symbol: _OBJC_CLASS_$_BarcodeDetectorManagerMlkit
Hello folks First of all installing react-native-camera with cocoapods is problematic It installs ob...
mlkit Barcode Scanning with CameraX not working on Android 10
Same issue after libraries update Tried on OnePlus 6T / Android 10 Is working with: Is not working w...
facenet How to add "unknown" class?
@avikj I'm currently classifying aligned faces as one of 3 different people Many of the images that ...
opencv4nodejs The specified module could not be found.
Yes I'm a total newbie with OpenCV But I guess you already figured that out! ;-) As you said ...
opencv4nodejs Missing functions and more
cv::exp should be available Will add cv::log and cv::goodFeaturesToTrack next time I find the time. ...
react native camera Changing Camera Type from back to front result in black screen in specific situation
a reliable temporary fix for this is to force remounting the component This can be achieved by setti...
howdy Error when adding a face (since Ubuntu 20.04)
For newbies: I checked which device was the IR camera using ffmpeg Mine was /dev/video2 ...
howdy Error while installing Ubuntu 19.04
PIP changed their entry point so /usr/bin/pip3 broke Linux distribution (if applicable): Ubuntu 19.0...
howdy Error when trying to use IR sensors on Manjaro (Arch-based) with HP Spectre
@boltgolt I think this error is cause by some IR Cameras return Grayscale instead of RGB image ...
howdy IR camera flashing loop after auth
So i found the bug After authentication IR camera continues flashing on/off on loop until disabled L...
keras Loading model with custom loss function: ValueError: 'Unknown loss function'
I solved this problem by adding 'custom_bojects' my loss function: I trained and saved a model that ...
keras Tensorflow backend - bug in model._make_predict_function(...)
I had this problem when doing inference in a different thread than where I loaded my model ...
keras Creating Model variable throws "AttributeError: 'Tensor' object has no attribute '_keras_history'"
@zaid478 oh I assumed you were doing it on coursera Anyway Hello all setup: Keras 2.0 Tensorflow 1.0...
tensorflow ImportError: cannot open shared object file: No such file or directory
@rhinsall I just found this out myself not sure if it's common knowledge but got around this by doin...
keras "<tensor> is not an element of this graph." when loading model.
I had a problem similar to that of @piraka9011 which was solved by calling model._make_predict_funct...
pytorch I can't import PyTorch, libomp.dylib can't be loaded.
brew install libomp solves the problem. 🐛 Bug I tried to install PyTorch but I can't use it ...
pytorch RuntimeError: cuda runtime error (59) : device-side assert triggered when running transfer_learning_tutorial
@soumith Hi I find the error it is due to my labels contain value -1 which is unacceptable in criter...
tensorflow At Runtime : "Error while reading resource variable softmax/kernel from Container: localhost"
I had the same issue in tensorflow 1.13.1 which I have resolved by creating a reference to the sessi...
tensorflow Mac + Python 3.6.1: Attempting to download mnist data results in CERTIFICATE_VERIFY_FAILED error
This might have also been because I recently switched to a new machine and it's still only partially...
tensorflow UnrecognizedFlagError: Unknown command line flag 'f'
I solved this issue by adding the line:'f' '' 'kernel') what this essent...
tensorflow FutureWarning: Deprecated numpy API calls in tf.python.framework.dtypes
@Akeaakar And for the time being pip install numpy<1.17 to revert to numpy version 1.16.4 ...