Solvedface_recognition Freeze your script with Pyinstaller

Hi,
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 yourscript.py.
  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 myscript.py
  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 name.py>'],
             pathex=['<path to working directory>'],
             binaries=face_models,
             datas=[],
             hiddenimports=['scipy._lib.messagestream', 'scipy', 'scipy.signal', 'scipy.signal.bsplines', 'scipy.special', 'scipy.special._ufuncs_cxx',
                            'scipy.linalg.cython_blas',
                            'scipy.linalg.cython_lapack',
                            'scipy.integrate',
                            'scipy.integrate.quadrature',
                            'scipy.integrate.odepack',
                            'scipy.integrate._odepack',
                            'scipy.integrate.quadpack',
                            'scipy.integrate._quadpack',
                            'scipy.integrate._ode',
                            'scipy.integrate.vode',
                            'scipy.integrate._dop', 'scipy._lib', 'scipy._build_utils','scipy.__config__',
                            'scipy.integrate.lsoda', 'scipy.cluster', 'scipy.constants','scipy.fftpack','scipy.interpolate','scipy.io','scipy.linalg','scipy.misc','scipy.ndimage','scipy.odr','scipy.optimize','scipy.setup','scipy.sparse','scipy.spatial','scipy.special','scipy.stats','scipy.version'],

             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher)

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

pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          name='<your python script name>',
          debug=False,
          strip=False,
          upx=True,
          runtime_tmpdir=None,
          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:

59
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...
22
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...
10
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 ...
242
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...
194
react native camera Could not find method compileOnly()
Just went through this myself Which implementation are you using RNCamera Steps to reproduce init a ...
107
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...
106
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 https://www.jitpack.io }...
93
react native camera Could not find method google() for arguments [] on repository container
set gradle-wrapper.properties set build.gradle Hi all I am having this error after i install react n...
92
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...
69
react native camera com.android.support:support-v4 version conflict
change implementation project(':react-native-camera') to: Actual behaviour I am using this library t...
40
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...
32
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...
31
facenet triplet training did not converged
Hi @davidsandberg I chose these parameters carefully and run a new experiment (20 days) The result i...
30
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...
27
facenet Error loading a frozen graph ( float incompatible with float_ref )
my code I froze the 20170131-234652 model using the freeze_graph.py but I cannot load it in C++ I fi...
26
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 ...
25
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 ...
17
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...
16
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...
14
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...
14
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 ...
12
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...
12
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 ...
11
opencv4nodejs fatal error: 'tesseract/baseapi.h' file not found
@GiulioPettenuzzo Let's say you receive output like this from your shell: The non-ideal ...
9
react native camera Pinch Zoom
the solution was provided by @cristianoccazinsp with the following answer Initial testing without us...
9
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)...
6
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...
4
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...
3
facenet How to add "unknown" class?
@avikj I'm currently classifying aligned faces as one of 3 different people Many of the images that ...
3
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 ...
3
opencv4nodejs Missing functions and more
cv::exp should be available Will add cv::log and cv::goodFeaturesToTrack next time I find the time. ...
3
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...
22
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 ...
13
howdy Error while installing Ubuntu 19.04
PIP changed their entry point so /usr/bin/pip3 broke Linux distribution (if applicable): Ubuntu 19.0...
4
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 ...
3
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...
926
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 ...
633
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 ...
516
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...
456
tensorflow ImportError: libcublas.so.10.0: 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...
395
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...
387
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 ...
380
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...
356
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...
355
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...
308
tensorflow UnrecognizedFlagError: Unknown command line flag 'f'
I solved this issue by adding the line: tf.app.flags.DEFINE_string('f' '' 'kernel') what this essent...
298
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 ...