python executable that has dependency on dlib not working - python

Hello everyone i have a python script that has dependency on dlib such as import dlib now i have created an executable out of it (using pyinstaller) and it works fine on my machine but gives ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed on another machine. and after digging out the line at which this occurs is basically importing dlib which makes me think dlib is not getting properly included in my executable. My dlib version 19.18.0 and the other machine i am trying to run exe on does'nt have python installed.Need help Error on another machine
F:\FaceRecogDemo\FaceRecogDemo\dist>recognizefaces.exe --debug --encodings ../encodings.pickle --image ../example1.jpg
Traceback (most recent call last):
File "D:\FaceRecogDemo\recognizefaces.py", line 2, in <module>
File "c:\programdata\anaconda3\envs\mywindowscv\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module
File "D:\FaceRecogDemo\face_recognition\__init__.py", line 7, in <module>
File "c:\programdata\anaconda3\envs\mywindowscv\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module
File "D:\FaceRecogDemo\face_recognition\api.py", line 4, in <module>
ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed.
[14720] Failed to execute script recognizefaces
My recognizefaces.py script
import face_recognition
import argparse
import pickle
import cv2
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-e", "--encodings", required=True,
help="path to serialized db of facial encodings")
ap.add_argument("-i", "--image", required=True,
help="path to input image")
ap.add_argument("-d", "--detection-method", type=str, default="cnn",
help="face detection model to use: either `hog` or `cnn`")
args = vars(ap.parse_args())
# load the known faces and embeddings
print("[INFO] loading encodings...")
data = pickle.loads(open(args["encodings"], "rb").read())
# load the input image and convert it from BGR to RGB
image = cv2.imread(args["image"])
rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# detect the (x, y)-coordinates of the bounding boxes corresponding
# to each face in the input image, then compute the facial embeddings
# for each face
print("[INFO] recognizing faces...")
boxes = face_recognition.face_locations(rgb,
model=args["detection_method"])
encodings = face_recognition.face_encodings(rgb, boxes)
# initialize the list of names for each face detected
names = []
# loop over the facial embeddings
for encoding in encodings:
# attempt to match each face in the input image to our known
# encodings
matches = face_recognition.compare_faces(data["encodings"],
encoding)
name = "Unknown"
# check to see if we have found a match
if True in matches:
# find the indexes of all matched faces then initialize a
# dictionary to count the total number of times each face
# was matched
matchedIdxs = [i for (i, b) in enumerate(matches) if b]
counts = {}
# loop over the matched indexes and maintain a count for
# each recognized face face
for i in matchedIdxs:
name = data["names"][i]
counts[name] = counts.get(name, 0) + 1
# determine the recognized face with the largest number of
# votes (note: in the event of an unlikely tie Python will
# select first entry in the dictionary)
name = max(counts, key=counts.get)
# update the list of names
names.append(name)
print(names)
Both my machines have windows 10 OS

Pyinstaller doesn't seem to be picking up dlib for some reason. When you construct your binary on the command line, try explicitly adding dlib to the bundle using the following flag pyinstaller --hidden-import dlib.
https://pyinstaller.readthedocs.io/en/stable/usage.html#what-to-bundle-where-to-search

I have resolved the issue, In my case it was due to direct compilation of dlib (I don't know why).
Here are steps:
Create a new environment
Install other requirements of your project
Make sure visual studio is installed on your development PC
pip install cmake
pip install face_recognition
Now you can use dlib, as face_recognition will install dlib as well.
Now you can create exe file, if still problem persists copy dlib folder from site_packages folder into folder where your exe file is placed.
In my case, it works on two other version of windows, where it was not working previously

The problem might also be in the environmental variable , can you check the %PATH% in the machine where you have executed the file. Multiple python versions and its configured correctly in the PATH.
The problem might also be due to the Visual C++ distribution , Check once you have the same distribution in both the machines.
Try to add the opencv DLL's in the path variables and check.The problem is a missing python3.dll in the anaconda distribution. You can download the python binaries here and extract dll out of the zip archive. Put it in a folder in your PATH (e.g. C:\Users\MyName\Anaconda3) and the import should work.
Can't import cv2; "DLL load failed"

Related

rembg library can't open 'i' error and also pickling error

I want to use rembg library to remove background of images. So I followed the instructions on github and try with rembg cli:
Python version: 3.9.12
rembg version: 1.0.27
OS: macOS Monterey 12.4
Chip: Apple M1 Silicon
https://github.com/danielgatis/rembg
rembg i man.jpeg output.png
Even if I'm on the right directory, I got this error message:
rembg: error: argument input: can't open 'i': [Errno 2] No such file or directory: 'i'
How can I resolve this? Is there any other methods?
Here is my other trial:
from rembg.bg import remove
from PIL import Image
input_path = 'man.jpeg'
output_path = 'output.png'
input = Image.open(input_path)
output = remove(input)
output.save(output_path)
It also gives that error message:
File "/Users/cucal/Desktop/coding/venvs/science/lib/python3.9/site-packages/torch/serialization.py", line 920, in _legacy_load
magic_number = pickle_module.load(f, **pickle_load_args)
_pickle.UnpicklingError: invalid load key, '<'.
Edit:
I tried this one https://github.com/danielgatis/rembg/issues/262 , but I don't know how to handle downloaded files. One is '.pth' other is '.onnx' files. When I copy these files to u2net in site-package, I'm getting the same pickle error.
Perhaps it does not work with jpeg (only png)

Reading text from image with Pytesseract gives bad path error

Im trying to read text from image with pytesseract. Im using mac.
I have install pytesseract with pip.
import cv2
import pytesseract
img = cv2.imread('slika1.png')
text = pytesseract.image_to_string(img)
print(text)
It gives me this error:
pytesseract.pytesseract.TesseractNotFoundError: tesseract is not installed or it's not in your PATH. See README file for more information.
when I do this:
import importlib.util
print(importlib.util.find_spec('pytesseract'))
It prints:
ModuleSpec(name='pytesseract', loader=<_frozen_importlib_external.SourceFileLoader object at 0x7f8a7837c160>, origin='/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pytesseract/__init__.py', submodule_search_locations=['/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pytesseract'])
So what should I do, what am I doing wrong?
Is there any other way to read text from image?
Try to open the module source file (as admin) and edit the path to the Tesseract exe file - set it with absolute path if needed. It should be a const in the top lines.
Something like this (on Win):
"C:\Program Files\Python36\Lib\site-packages\pytesseract\pytesseract.py"
Set the path: ...
pytesseract.tesseract_cmd = r"D:\OCR\tesseract.exe"
https://github.com/Twenkid/ComputerVision_Pyimagesearch_OpenCV_Dlib_OCR-Tesseract-DL/blob/master/OCR_Tesseract/ocr.py

Is there any direct command to install pyopenpose?

I am trying to use Openpose from windows and i need to run .py file. But i couldn't find any command to install pyopenpose module So where can I find pyopenpose module?
I tried this command on cmd:
C:\openpose\examples\tutorial_api_python>python 01_body_from_image.py
I get the error :
Error: OpenPose library could not be found. Did you enable `BUILD_PYTHON` in CMake and have this Python script in the right folder?
Traceback (most recent call last):
File "01_body_from_image.py", line 26, in <module>
raise e
File "01_body_from_image.py", line 17, in <module>
import pyopenpose as op
ModuleNotFoundError: No module named 'pyopenpose'
The error in general is that PyOpenPose cannot be found (an error similar to: ImportError: cannot import name pyopenpose). Ensure first that BUILD_PYTHON flag is set to ON. If the error persists, check the following:
In the script you are running, check for the following line, and run the following command in the same location as where the file is.
Ubuntu/OSX:
sys.path.append('../../python');
ls ../../python/openpose
Check the contents of this location. It should contain one of the following files:
pyopenpose.cpython-35m-x86_64-linux-gnu.so
pyopenpose.so
If you do not have any one of those, you may not have compiled openpose successfully, or you may be running the examples, not from the build folder but the source folder. If you have the first one, you have compiled PyOpenPose for Python 3, and have to run the scripts with python3, and vice versa for the 2nd one. Follow the testing examples above for exact commands.
Windows:
Problem 1: If you are in Windows, and you fail to install the required third party Python libraries, it might print an error similar to: Exception: Error: OpenPose library could not be found. Did you enable BUILD_PYTHON in CMake and have this Python script in the right folder?. From GitHub issue #941:
I had a similar issue with Visual Studio (VS). I am pretty sure that the issue is that while you are compiling OpenPose in VS, it tries to import cv2 (python-opencv) and it fails. So make sure that if you open cmd.exe and run Python, you can actually import cv2 without errors. I could not, but I had cv2 installed in a IPython environment (Anaconda), so I activated that environment, and then ran (change this to adapt it to your VS version and location of OpenPose.sln):
C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild.exe
C:\path\to\OpenPose.sln
Problem 2: Python for Openpose needs to be compiled in Release mode for now. This can be done in Visual Studio. Once that is done check this line:
sys.path.append(dir_path + '/../../python/openpose/Release');
dir ../../python/openpose/Release
Check the contents of this location. It should contain one of the following files:
pyopenpose.cp36-win_amd64.pyd
pyopenpose.pyd
If such a folder does not exist, you need to compile in Release mode as seen above. If you have the first one, you have compiled PyOpenPose for Python 3, and have to run the scripts with python3, and vice versa for the 2nd one. Follow the testing examples above for exact commands. If that still does not work, check this line:
os.environ['PATH'] = os.environ['PATH'] + ';' + dir_path + '/../../x64/Release;' + dir_path + '/../../bin;'
dir ../../x64/Release
dir ../../bin
Ensure that both of these paths exist, as PyOpenPose needs to reference those libraries. If they don't exist, change the path so that they point to the correct location in your build folder.

Using Image (Pillow)/Pytesseract (Python): FineNotFound: [WinError 2] The system cannot find the file specified

On a little project I had an issue with on of the two modules, so I created a short code to see where the problem comes from.
Here is my code:
import pytesseract
from PIL import Image
text= pytesseract.image_to_string(Image.open('pict.jpg'))
With this, I get the same error:
FileNotFoundError: [WinError 2]The system cannot find the file specified
and PyScripter open the subprocess.py file and show me the following line:
# Start the process
try:
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
# no special security
None, None,
int(not close_fds),
creationflags,
env,
cwd,
startupinfo)
When I googled this issue, it looked like my version of pytesseract was causing this. I tried to install different versions of pytesseract or Pillow, but the error still occurs.
What should I do ? How can I be sure that my installation is proper ?
Thanks.
EDIT1:
I tried adding this to make sure the module directory is in the system path:
sys.path.insert(0,'C:\Python34\Lib\site-packages\pytesseract')
It looks like pytesseract can't find your installation of Tesseract. Ensure that the folder containing tesseract.exe is in your system path so that the module can actually run the binary.
If you don't want to modify your environment variables, you can manually specify the full path:
import pytesseract
pytesseract.tesseract_cmd = r'C:\Path\To\tesseract.exe'
# ^ the `r` is needed to have the backslashes
# be interpreted as literal backslashes
# The rest of your code

python imaging library cannot save PNG to JPG

I installed PIL 1.1.7 from source on Mac OSX.
I also installed required libraries from Macports.
Using python 2.6.
After installing PIL, I could successfully run the selftest.py (all tests pass)
But when I try running the following code, I find that I am not able to convert PNG to JPG. I am however able to convert PNG to GIF, PNG to PPM. I can also read JPGs.
import os
import sys
import Image
for infile in sys.argv[1:]:
f, e = os.path.splitext(infile)
outfile = f + ".jpg"
print outfile
if infile != outfile:
try:
Image.open(infile).save(outfile, 'jpg') #Note: gif or ppm works
except IOError:
print "cannot convert", infile
if os.path.exists(outfile):
print 'cleaning up...'
os.remove(outfile)
** update with stack trace. Looks like encoder is missing. I did however install libjpeg thru macport.
Cleaning up...
Traceback (most recent call last):
File "convert_to_jpeg.py", line 15, in <module>
Image.open(infile).save(outfile, 'jpeg')
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PIL/Image.py", line 1439, in save
save_handler(self, fp, filename)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PIL/JpegImagePlugin.py", line 471, in _save
ImageFile._save(im, fp, [("jpeg", (0,0)+im.size, 0, rawmode)])
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PIL/ImageFile.py", line 495, in _save
e = Image._getencoder(im.mode, e, a, im.encoderconfig)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PIL/Image.py", line 401, in _getencoder
raise IOError("encoder %s not available" % encoder_name)
IOError: encoder jpeg not available
Use jpeg not jpg for the format identifier.
Thanks to #jterrace for suggesting homebrew.
Solution:
Install homebrew
brew install python
brew install pil
It appears you have to take some additional steps to work with JPG with PIL on Mac OSX.
I've found some links, but nothing you couldn't also find on google:
http://websaucesoftware.com/uncategorized/getting-pil-installed-on-os-x-10-6-snow-leopard-with-jpeg-support
http://code.davidjanes.com/blog/2009/11/16/pil-libjpeg-jpeg-and-mac-osx-snow-leopard/
You are playing my song.
I wrestled with JPEG support in PIL for weeks before I landed on this link: http://proteus-tech.com/blog/cwt/install-pil-in-snow-leopard/
It's the only thing that worked. The gory details of my un-installation and re-installation process are here: http://www.thetoryparty.com/2010/08/31/pil-on-snow-leopard-_jpeg_resync_to_restart-error/
The summary of what I did:
1) Force the gcc and gcov paths to 4.2 (they had been set to 4.0 to get MySQLdb to install)
2) In my .profile, commented out certain ARCHFLAGS lines I had kicking around (possibly optional step?)
3) Picked through my system to delete EVERYTHING called anything like “libjpeg,” “PIL” or “Imaging" -- to clean house
4) Followed the steps at the above proteus-tech link, starting from downloading a fresh libjpeg.
Good luck! You can do it!
(P.S.: Note that if you WERE getting an error from selftest.py -- specifically "IOError: decoding error when reading image file" -- and you WEREN'T able to load a JPEG, then this is the process that solved THAT problem:
http://www.thetoryparty.com/2011/04/07/pil-and-jpeg-decoding-error-the-revenge/ It may be of interest if you run into more trouble later.
Note both problems pertain to libjpeg needing to be built with "-arch i386" and not "-arch x86_64." So that's the fun of 64 bit for you!)

Categories