Python Image Library: AttributeError: 'NoneType' object has no attribute XXX - python-imaging-library

I opened a picture with PIL, but when I tried to use split() to split the channels I got following error:
AttributeError: 'NoneType' object has no attribute 'bands'
import Image
img = Image.open('IMG_0007.jpg')
img.split()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/home/blum/<ipython console> in <module>()
/usr/lib/python2.6/dist-packages/PIL/Image.pyc in split(self)
1495 "Split image into bands"
1496
-> 1497 if self.im.bands == 1:
1498 ims = [self.copy()]
1499 else:
AttributeError: 'NoneType' object has no attribute 'bands'

With googling I found this comment on SO, stating that PIL is sometimes 'lazy' and 'forgets' to load after opening. So you have to do it like this:
import Image
img = Image.open('IMG_0007.jpg')
img.load()
img.split()
Please +1 also the original comment! This person did the real work.

My problem was that PIL was not installed correctly. When trying to read a png I'd get that error. My compilation summary yielded
--------------------------------------------------------------------
PIL 1.1.7 SETUP SUMMARY
--------------------------------------------------------------------
version 1.1.7
platform linux2 2.7.3 (default, Apr 21 2012, 01:05:55)
[GCC 4.6.3]
--------------------------------------------------------------------
*** TKINTER support not available
*** JPEG support not available
*** ZLIB (PNG/ZIP) support not available <===============
*** FREETYPE2 support not available
*** LITTLECMS support not available
--------------------------------------------------------------------
I then opted to "pip uninstall pil" and used the Synaptic Package Manager instead. That fixed it.

Related

Wordcloud installation on Windows (PIL, pillow)

Basically, I am trying to generate simple word cloud using Python on Windows. Hence, I have installed wordcloud as:
pip install wordcloud
I am trying to run the simplest example from here as below:
import os
from os import path
from wordcloud import WordCloud
# get data directory (using getcwd() is needed to support running example in generated IPython notebook)
d = path.dirname(__file__) if "__file__" in locals() else os.getcwd()
# Read the whole text.
text = open(path.join(d, 'constitution.txt')).read()
# Generate a word cloud image
wordcloud = WordCloud().generate(text)
# Display the generated image:
# the matplotlib way:
import matplotlib.pyplot as plt
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
# lower max_font_size
wordcloud = WordCloud(max_font_size=40).generate(text)
plt.figure()
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
plt.show()
The error I got:
Traceback (most recent call last):
File "C:\Users\XXXXX\test_wordcloud.py", line 13, in <module>
wordcloud = WordCloud().generate(text)
File "C:\Anaconda3\lib\site-packages\wordcloud\wordcloud.py", line 639, in generate
return self.generate_from_text(text)
File "C:\Anaconda3\lib\site-packages\wordcloud\wordcloud.py", line 621, in generate_from_text
self.generate_from_frequencies(words)
File "C:\Anaconda3\lib\site-packages\wordcloud\wordcloud.py", line 454, in generate_from_frequencies
max_font_size=self.height)
File "C:\Anaconda3\lib\site-packages\wordcloud\wordcloud.py", line 503, in generate_from_frequencies
font = ImageFont.truetype(self.font_path, font_size)
File "C:\Anaconda3\lib\site-packages\PIL\ImageFont.py", line 959, in truetype
return freetype(font)
File "C:\Anaconda3\lib\site-packages\PIL\ImageFont.py", line 956, in freetype
return FreeTypeFont(font, size, index, encoding, layout_engine)
File "C:\Anaconda3\lib\site-packages\PIL\ImageFont.py", line 219, in __init__
if core.HAVE_RAQM:
File "C:\Anaconda3\lib\site-packages\PIL\ImageFont.py", line 58, in __getattr__
raise ImportError("The _imagingft C module is not installed")
ImportError: The _imagingft C module is not installed
The PIL and Python versions on my side are:
from PIL import Image, ImageDraw, ImageFilter, ImageFont
print('PIL',PIL.__version__)
import sys
print(sys.version)
as:
PIL 9.2.0
3.7.13 (default, Mar 28 2022, 08:03:21) [MSC v.1916 64 bit (AMD64)]
Any suggestions ?
Thanks
On Windows 10, install the FreeType binding. Hopefully, it is resolved by re-installing the Pillow with disabling the pip cache as:
pip install freetype-py
pip uninstall pillow
pip install --no-cache-dir pillow
Once pillow is recompiled, everything worked properly for me!
In addition, the following check:
from PIL import features
print(features.check('freetype2'))
was False before the recent PIL re-installation. However, it is converted
into True after above listed steps. By the way, no need to reboot!

Getting started with SciPy and first example doesn't run

Environment is Ubuntu 12.x LTS 64 bit. I ran the install as follows :
sudo apt-get install python-numpy python-scipy python-matplotlib ipython ipython-notebook python-pandas python-sympy python-nose
Everything installed great, and I tried out the 'getting started' example only to come upon this error as if my env. is't set correctly..
See orig # http://www.scipy.org/getting-started.html
usernamep#ubuntudev:~$ ipython --pylab
Python 2.7.3 (default, Sep 26 2013, 20:03:06)
Type "copyright", "credits" or "license" for more information.
IPython 0.12.1 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
Welcome to pylab, a matplotlib-based Python environment [backend: TkAgg].
For more information, type 'help(pylab)'.
In [1]: from scipy import special, optimize
In [2]: f = lambda x: -special.jv(3,x)
In [3]: sol = optimize.minimize(f, 1.0)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/home/user/<ipython-input-3-ea43eb308d3c> in <module>()
----> 1 sol = optimize.minimize(f, 1.0)
AttributeError: 'module' object has no attribute 'minimize'
In [4]:
Do I need to reform their example's import? Checking their docs now...
optimize.minimize was introduced in Scipy v.0.11 (see http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html ).
On Debian, that would mean that you need Jessie or better. On Ubuntu, you appear to need raring or better.
Almost certainly the scipy you installed using apt-get is simply too old to have minimize: (0.10, I'd guess). The code works for me:
>>> from scipy import special, optimize
>>> def f(x): return -special.jv(3,x)
>>> sol = optimize.minimize(f, 1.0)
>>> sol
status: 0
success: True
njev: 17
nfev: 51
hess_inv: array([[ 4.70024446]])
fun: -0.43439442684052476
x: array([ 4.20118891])
message: 'Optimization terminated successfully.'
jac: array([ -3.72529030e-09])
I think you'll be better off using pip to install the stack.
python-scipy package in the Ubuntu 12 is a bit old. I think it is ver 0.9.0. The optimize.minimize function was added to scipy ver 0.11.0.

iptest3 with IPython

I'm brand new to Python programming and trying to get myself a functional base from which I can run things like the IPython Notebook which looks pretty exciting.
Thus far I have both Python 2.7 and 3.3 from python.org installed in OS X 10.6 (Snow Leopard) as well as ActiveTcl 8.5.13. Almost everything that I've tried thus far works as expected. I'm focused on learning 3.3, but want to have the option of using 2.7 too. I read up in several documents that I need to start gaining access to PyPI packages using a Python package manager and that distribute is the one I should use for 3k. So I installed that according to the documentation I found and it seemed to work fine.
I also installed pip as directed, and a number of others.
At this point, I have:
$ pip freeze
distribute==0.6.34
ipython==0.13.1
nose==1.2.1 (installed after IPython)
pexpect==2.4 (installed after IPython)
pyflakes3k==0.4.3
readline==6.2.4.1 (installed after IPython)
At this point, I'm doing this from ipython.org guidance
And when I did $ easy_install pexpect, I got a bunch of errors:
$ easy_install pexpect
Searching for pexpect
Reading http://pypi.python.org/simple/pexpect/
Reading http://pexpect.sourceforge.net/
Reading http://sourceforge.net/project/showfiles.php?group_id=59762
Best match: pexpect 2.4
Downloading http://pypi.python.org/packages/source/p/pexpect/pexpect-2.4.tar.gz#md5=fe82d69be19ec96d3a6650af947d5665
Processing pexpect-2.4.tar.gz
Writing /var/folders/td/td0Sh8EfGFuMCnKex1v+q++++TI/-Tmp-/easy_install-s4dtyy/pexpect-2.4/setup.cfg
Running pexpect-2.4/setup.py -q bdist_egg --dist-dir /var/folders/td/td0Sh8EfGFuMCnKex1v+q++++TI/-Tmp-/easy_install-s4dtyy/pexpect-2.4/egg-dist-tmp-5h5cg4
File "build/bdist.macosx-10.6-intel/egg/fdpexpect.py", line 36
raise ExceptionPexpect, 'The fd argument is not a valid file descriptor.'
^
SyntaxError: invalid syntax
File "build/bdist.macosx-10.6-intel/egg/FSM.py", line 77
return `self.value`
^
SyntaxError: invalid syntax
File "build/bdist.macosx-10.6-intel/egg/pexpect.py", line 82
except ImportError, e:
^
SyntaxError: invalid syntax
zip_safe flag not set; analyzing archive contents...
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pexpect-2.4-py3.3.egg/fdpexpect.py", line 36
raise ExceptionPexpect, 'The fd argument is not a valid file descriptor.'
^
SyntaxError: invalid syntax
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pexpect-2.4-py3.3.egg/FSM.py", line 77
return `self.value`
^
SyntaxError: invalid syntax
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pexpect-2.4-py3.3.egg/pexpect.py", line 82
except ImportError, e:
^
SyntaxError: invalid syntax
Adding pexpect 2.4 to easy-install.pth file
Installed /Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pexpect-2.4-py3.3.egg
Processing dependencies for pexpect
Finished processing dependencies for pexpect
That looks bad to me (although I don't yet have the expertise to really interpret it), and so I'm not sure if I have a complete install of pexpect.
After installing nose (before pexpect as per URL above), I tried running iptest and iptest3 from the command line, and both failed to find the command, but after I did easy_install ipython again (after nose), I noticed that this install added iptest3 (as well as ipcluster3 and a few other scripts) to my path, and now my bash shell can find iptest3, but when I run it, I get some more bad-looking output:
$ iptest3
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.3/bin/iptest3", line 9, in <module>
load_entry_point('ipython==0.13.1', 'console_scripts', 'iptest3')()
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/distribute-0.6.34-py3.3.egg/pkg_resources.py", line 343, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/distribute-0.6.34-py3.3.egg/pkg_resources.py", line 2308, in load_entry_point
return ep.load()
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/distribute-0.6.34-py3.3.egg/pkg_resources.py", line 2014, in load
entry = __import__(self.module_name, globals(),globals(), ['__name__'])
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/IPython/__init__.py", line 43, in <module>
from .config.loader import Config
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/IPython/config/__init__.py", line 16, in <module>
from .application import *
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/IPython/config/application.py", line 31, in <module>
from IPython.config.configurable import SingletonConfigurable
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/IPython/config/configurable.py", line 26, in <module>
from .loader import Config
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/IPython/config/loader.py", line 27, in <module>
from IPython.utils.path import filefind, get_ipython_dir
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/IPython/utils/path.py", line 25, in <module>
from IPython.utils.process import system
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/IPython/utils/process.py", line 27, in <module>
from ._process_posix import _find_cmd, system, getoutput, arg_split
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/IPython/utils/_process_posix.py", line 22, in <module>
from IPython.external import pexpect
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/IPython/external/pexpect/__init__.py", line 2, in <module>
import pexpect
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pexpect-2.4-py3.3.egg/pexpect.py", line 82
except ImportError, e:
^
SyntaxError: invalid syntax
After doing all that, I noted that my /Library/Frameworks/Python.framework/Versions/Current had been pointing to 2.7, and I guessed that that might be related to my problems and changed the symbolic link to point to 3.3, but iptest3 still fails with the error above.
Any other thoughts on what to do to fix this? It's clear that iptest is pretty important to doing anything else (like IPython Notebook) I want to do.
There is a py3-compatible fork of pexpect called pexpect-u (the u is for unicode, the main difference between the two). You need this to run the pexpect-based parts of IPython on Python 3.
Should be a simple
pip install pexpect-u
side note: pexpect-u is by IPython developer Thomas Kluyver, who did most of the heavy lifting bringing py3 compatibility to IPython.

Ming 0.3.2 Installs and Imports but Crashes

After installing Ming 0.3.2, I tested the installation by running the following code:
>>> from ming.datastore import DataStore
>>> bind = DataStore('mongodb://localhost:27017/', database='tutorial')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() got an unexpected keyword argument 'database'
>>> ^D
I looked at the installation files and in the datastore.py file I found that the class's constructor did not contain a "database" argument.
class DataStore(object):
def __init__(self, bind, name, authenticate=None):
self.bind = bind
self.name = name
self._authenticate = authenticate
self._db = None
I then installed Ming 0.3.0 to look at the datastore.py file and found the DataStore class to match the documentation (it contained a database arg) and then tried that version where I encountered other complications.
I use easy_install to install Ming and I have a good install of mongodb and pymongo running. I run these on OS X Lion. Any advise on getting Ming running would be appreciated.
I think there may be a conflict with the newest version of pymongo and ming.
bind = DataStore('mongodb://localhost:27017/', name='test') gets me a bit further along, but I ended up just using pymongo by itself.
I've met the same issue. Here are the steps I've tried, and it works! Hopes it works for your environment too.
Uninstall the Ming 0.3.2 version by : pip uninstall Ming
Install 0.3.0 by: pip install -Iv http://downloads.sourceforge.net/project/merciless/0.3.0/Ming-0.3.0.tar.gz
Try the example on the Ming office website again. There will be another error
Traceback (most recent call last):
File "tutorial.py", line 1, in <module>
from ming.datastore import DataStore
File "/home/me/work/deploy/test/local/lib/python2.7/site-packages/ming/init.py", line 3, in <module>
from session import Session
File "/home/me/work/deploy/test/local/lib/python2.7/site-packages/ming/session.py", line 7, in <module>
from pymongo.son import SON
ImportError: No module named son
change the line 7 of "/home/me/work/deploy/test/local/lib/python2.7/site-packages/ming/session.py" to from bson.son import SON
try again. and it will works.
Here is the link I've referenced. It's a Japanese webpage, but you can translate it to English by google translator.
http://ryooo321.blogspot.com/2012/05/macsleepymongoose.html
try to remove database=.
In [8]: from ming.datastore import DataStore
In [9]: bind = DataStore('mongodb://grid:27017/', 'tutorial')
In [10]: bind.name
Out[10]: 'tutorial'

What is the correct way to load a dll library in Postgres PL/Python?

The following gives an error
drop function testing();
CREATE FUNCTION testing()
RETURNS text
AS $$
import ctypes
try:
ctypes.windll.LoadLibrary("D:\\jcc.dll")
except:
import traceback
plpy.error(traceback.format_exc())
return ''
$$ LANGUAGE plpythonu;
select testing();
Error message:
ERROR: ('Traceback (most recent call last):\n File "<string>", line 5, in __plpython_procedure_testing_1517640\n File "D:\\Python26\\Lib\\ctypes\\__init__.py", line 431, in LoadLibrary\n return self._dlltype(name)\n File "D:\\Python26\\Lib\\ctypes\\__init__.py", line 353, in __init__\n self._handle = _dlopen(self._name, mode)\nWindowsError: [Error 126] The specified module could not be found\n',)
It works fine in a python interpretor.
Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import ctypes
>>> ctypes.windll.LoadLibrary("D:\\jcc.dll")
<WinDLL 'D:\jcc.dll', handle 410000 at 1d9cb10>
>>>
"The specified module could not be found" is one of those helpful error messages Windows emits that doesn't always mean what you think it means.
Windows will produce that message if the DLL you tried to load or any dll it depends on could not be found.
Since PostgreSQL runs in its own user account it has a different PATH to that which your interpreter runs in when you're testing. If jcc.dll depends on (say) c:\jccsupportfiles\aaa.dll and c:\jccsupportfiles is on your PATH but not the Pg server's PATH, that would explain your problem.
Try using Dependency Walker (depends.exe) to determine which DLLs your DLL requires and where they are. See if it's a PATH issue.
Rather than messing with the Pg server's PATH, consider just putting all the DLLs required by jcc.dll in the same directory as jcc.dll. IIRC Windows will always look in the same directory as the module it's loading first when it tries to load a module it depends on.