python imaging library cannot save PNG to JPG - python

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!)

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)

UnicodeDecodeError: 'charmap' codec| Error during installation of pip python-stdnum==1.8

I am fairly new to programming, so please bear with me.
While I was installing some required packages for a module that I'm using, I wasn't able to install python-stdnum==1.8.
I got the following error message:
File "C:\Users\59996\AppData\Local\Programs\Python\Python37\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 967: character maps to <undefined>
----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
Is there anything I can do to still be able to install the package?
Any help would be greatly appreciated. Thanks in advance!
If it's for the Odoo 14 install on Windows, the issue is in the "requirements.txt"
Change "python-stdnum==1.8" to "python-stdnum==1.8.1" (even if the answer of Federico Baù is working by the way)
then another issue will appear so change "psutil==5.6.6" to "psutil==5.6.7"
still in the "requirements.txt"
source: https://github.com/odoo/odoo/issues/62919
Best regards
I ran to the same problem while installing Odoo Dependencies in Windows, but after some tacke I found a solution.
It's a old bug with stdnum 1.8 --> stdnum 1.8 installation fails on windows.
setup.py: Open README with utf-8 encoding.
Solution
Go to arthurdejong.org/python-stdnum/ and find python-stdnum-1.8.tar.gz
Download the Zip in a folder, rename it from python-stdnum-1.8.tar.gz to python-stdnum-1.8.tar_.gz (Just to avoid name collision).
Then create the following Python Script (in the same directory):
import tarfile
def open_tarfile_function(tarfile_file_name):
open_tarfile=tarfile.open("python-stdnum-1.8.tar_.gz")
open_tarfile.extractall(path='stdnum')
open_tarfile.close()
open_tarfile_function('data.tgz')
It will create a folder named stdnum, open it and then open setup.py, go to line 37 and modify from this:
with open(os.path.join(base_dir, 'README'), 'r') as fp:
long_description = fp.read()
To this:
with open(os.path.join(base_dir, 'README'), 'rb') as fp:
long_description = fp.read().decode('utf-8')
Save it.
Now in the same Directory run this code:
import tarfile
import os.path
def make_tarfile(output_filename, source_dir):
with tarfile.open(output_filename, "w:gz") as tar:
tar.add(source_dir, arcname=os.path.sep)
output_filename = "python-stdnum-1.8.tar.gz"
source_dir = "stdnum\python-stdnum-1.8"
make_tarfile(output_filename, source_dir)
This will create file python-stdnum-1.8.tar.gz copy the Absolute Path
Go to your Python Environment and run:
pip install D:\Odoo\Odoo_instance_one\python-stdnum-1.8.tar.gz
Obviously replace the Absolute Path with your absolute path.
First,you can use the online installation, use the command pip install python-stdnum==1.8.
Second,you can download whl file of python-stdnum from here.
For example download to F:/file.
Then use command pip install F:/file/python_stdnum-1.15-py2.py3-none-any.whl to install.
python-stdnum 1.8 is the previous version, there is no corresponding whl file anymore.
In general, the previous version corresponds to the python version is relatively low, so if you use pip install python-stdnum==1.8 to install, there may be problems, because your current python is 3.7, which is relatively new.

FileNotFoundError: [Errno 2] when packaging for PyPI

I have uploaded a simple python package in https://test.pypi.org. When I download this with pip and try yo run I get FileNotFoundError: [Errno 2] File b'data/spam_collection.csv' does not exist: b'data/spam_collection.csv'. Earlier I had issues with uploading the csv file when packaging. See my question in Could not upload csv file to test.pypi.org. Now after installing the package with pip I run pip show -f bigramspamclassifier. I get the csv file listed. Therefore, I believe the file has been uploaded. I think the issue is with reading the file in my python file in the package. What should be the path to the csv file in SpamClassifier.py?
pip show -f bigramspamclassifier
Version: 0.0.3
Summary: A bigram approach for classifying Spam and Ham messages
Home-page: ######
Author: #####
Author-email: #######
Location: /home/kabilesh/PycharmProjects/TestPypl3/venv/lib/python3.6/site-packages
Requires: nltk, pandas
Required-by:
Files:
bigramspamclassifier-0.0.3.dist-info/INSTALLER
bigramspamclassifier-0.0.3.dist-info/LICENSE
bigramspamclassifier-0.0.3.dist-info/METADATA
bigramspamclassifier-0.0.3.dist-info/RECORD
bigramspamclassifier-0.0.3.dist-info/WHEEL
bigramspamclassifier-0.0.3.dist-info/top_level.txt
bigramspamclassifier/SpamClassifier.py
bigramspamclassifier/__init__.py
bigramspamclassifier/__pycache__/SpamClassifier.cpython-36.pyc
bigramspamclassifier/__pycache__/__init__.cpython-36.pyc
bigramspamclassifier/data/spam_collection.csv
My project file structure
Path to csv in SpamClassifier.py file #This what I want to know
def classify(self):
fullCorpus = pd.read_csv("data/spam_collection.csv", sep="\t", header=None)
fullCorpus.columns = ["lable", "body_text"]
Your script is attempting to load the spam_collection.csv file from a relative path. Relative paths are loaded relative to where python is being invoked, not where the source file is.
This means that when you're running your module from the bigramspamclassifier directory, this will work. However, once your module is pip-installed, file will no longer be relative to where you're running your code from (it will be buried somewhere in your installed libraries).
You can instead load relative to the source file by doing something like:
import os
this_dir, this_filename = os.path.split(__file__)
DATA_PATH = os.path.join(this_dir, "data", "spam_collection.csv")
fullCorpus = pd.read_csv(DATA_PATH, sep="\t", header=None)

OpenALPR Python binding failing when trying to load dll

After downloading the precompiled binaries for Windows of the openALPR library, running the setup.py included in the source code to install it, and running the python_test.bat included in the precompiled binaries directory I get the following error:
File "C:\Users\rhenriquez\AppData\Local\Programs\Python\Python37-32\lib\site-packages\openalpr\openalpr.py", line 51, in __init__
self._openalprpy_lib = ctypes.cdll.LoadLibrary("libopenalprpy.dll")
File "C:\Users\rhenriquez\AppData\Local\Programs\Python\Python37-32\lib\ctypes\__init__.py", line 434, in LoadLibrary
return self._dlltype(name)
File "C:\Users\rhenriquez\AppData\Local\Programs\Python\Python37-32\lib\ctypes\__init__.py", line 356, in __init__
self._handle = _dlopen(self._name, mode)
OSError: OSError: [WinError 193] %1 is not a valid Win32 application
When I started to run the script at first the error was WinError 126 and then I noticed that the dll that the script was trying to call (openalprpy.dll) didn't had "lib" at the beginning of its name, so I added it to the dll's name. Then it started to send me WinError 193, and I've been clueless on what else to do or what am I doing wrong from then on.
Any help would be appreciated.
EDIT: So I tried this with the 32-bit version and it gives the same error you are encountering. This appears to be an issue with trying to import a 32-bit .dll while using 64-bit python, or vice-versa, as seen in Python Ctypes Load Library
/EDIT
I did get it to work on my system... with a few modifications, this package is not as "plug and play" as it should be.
I don't know where I went right, so I'll just list what I did:
Download the pre-compiled biniaries from releases (I used openalpr-2.3.0-win-64bit.zip) https://github.com/openalpr/openalpr/releases
Download the project itself, https://github.com/openalpr/openalpr
Unzip both.
Goto the bindings folder in openalpr-master cd C:\openalpr-master\openalpr-master\src\bindings\python and run python setup.py install to make the bindings.
Then navigate to the project folder in site-packages, most likely C:\Users\rhenriquez\AppData\Local\Programs\Python\Python37-32\lib\site-packages\openalpr\ and open openalpr.py in IDLE,
here you can change line 51 from self._openalprpy_lib = ctypes.cdll.LoadLibrary("libopenalprpy.dll") to self._openalprpy_lib = ctypes.cdll.LoadLibrary("openalprpy.dll") since it appears other links are broken if you change the file name.
I also found it beneficial to change line 90 to except Exception: since it did not want to import correctly and was not raising an ImportError.
After that the python_test.bat worked correctly.
Namespace(config='openalpr.conf', country='us', plate_image='samples/us-1.jpg', runtime_data='runtime_data')
Using OpenALPR 2.3.0
Image size: 497x372
Processing Time: 561.825989
Plate #1
Plate Confidence
- THECAR 92.207481
- THEGAR 81.348961
- HECAR 80.229317
- TMECAR 78.159492
- THE0AR 77.702461
- THECAB 77.389000
- THEAR 76.510017
Press any key to continue . . .

Missing files for `magic` library on Windows

I need to get mime type for some files on windows, so i've installed python-magic (on 32-bit python 2.7.3).
It depends on unix magic library.
Author instructs to get regex2.dll, zlib1.dll and magic1.dll from gnuwin32 project.
So i saved the files to a folder and added the folder to my system PATH.
Now when i execute magic methods, i get missing file exception:
import magic
print(magic.Magic())
Traceback (most recent call last):
File "C:/Users/Admin/PycharmProjects/lex/lex.py", line 367, in <module>
test_magic()
File "C:/Users/Admin/PycharmProjects/lex/lex.py", line 364, in test_magic
print(magic.Magic())
File "C:\Python27\lib\site-packages\python_magic-0.4.3-py2.7.egg\magic.py", line 52, in __init__
magic_load(self.cookie, magic_file)
File "C:\Python27\lib\site-packages\python_magic-0.4.3-py2.7.egg\magic.py", line 188, in magic_load
return _magic_load(cookie, coerce_filename(filename))
File "C:\Python27\lib\site-packages\python_magic-0.4.3-py2.7.egg\magic.py", line 139, in errorcheck
raise MagicException(err)
magic.MagicException: could not find any magic files!
DLLs are in the PATH, i tried debugging and magic1.dll is located correctly, but somewhere inside library throws an exception.
Inside the gnuwin32 package i've found magic and magic.mgc. I placed them to the same folder, and got WindowsError: [Error 126] on
libmagic = None
# Let's try to find magic or magic1
dll = ctypes.util.find_library('magic') or ctypes.util.find_library('magic1')
# This is necessary because find_library returns None if it doesn't find the library
if dll:
libmagic = ctypes.CDLL(dll)
This obviously happens because python tries to open magic file as dll, which is plain text. After adding .dll to filenames in the code i get the same magic.MagicException: could not find any magic files!.
What files am i missing?
UPDATE:
C:\Users\Admin>file C:\123.zip -m magic
file: could not find any magic files!
C:\Users\Admin>file C:\123.zip -m "C:\#DEV\#LIB\#Magic\GetGnuWin32\bin\magic"
C:\123.zip; ASCII text, with no line terminators
C:\Users\Admin>cd C:\#DEV\#LIB\#Magic\GetGnuWin32\bin
C:\#DEV\#LIB\#Magic\GetGnuWin32\bin>file C:\123.zip -m magic
C:\123.zip; ASCII text, with no line terminators
UPDATE 2 (SOLVED):
print(magic.Magic())
magic.MagicException: could not find any magic files!
print(magic.Magic(magic_file = 'magic'))
<magic.Magic instance at 0x02A5E198>
just had to specify file explicitly
For future google visitors: Another solution is setting the %MAGIC% enviroment variable in the systems setting to point to the magic file, for me it was:
"c:\Program Files (x86)\GnuWin32\share\misc\magic"
No need to hardcode the path in your program!
Path to magic file has to be explicitly passed to the constructor.
magic_object = magic.Magic(magic_file = 'path_to_magic_files/magic'))
As the python-magic problems seems to be quite common, here a working solution fo future googlers:
After testing most solutions without altering the source-code, I found the following to get python-magic working out of the box:
Install GnuWin32 file first
Set the environment variable MAGIC=path\to\gnuwin32\share\misc\magic
Assure all installed executables/libraries to be accessible via the
PATH
Install python-magic via pip
Please try install this package:
pip install python-magic-bin
try this:
pip uninstall python-magic
pip uninstall python-magic-bin
pip install python-magic
pip install python-magic-bin
which means install python-magic-bin after python-magic
reference:https://github.com/ahupp/python-magic/issues/248

Categories