I installed PIL 1.1.7 using the executable for Python 2.7. But when I run this code :
import requests
from PIL import *
def main() :
target = "http://target/image.php" #returns binary data for a PNG.
cookies = {"mycookie1", "mycookie2"}
r = requests.get(target, cookies=cookies)
im = Image.open(r.content) #r.content contains binary data for the PNG.
print im
if __name__ == "__main__" :
main()
It gives the error :
Traceback (most recent call last):
File "D:\Programming\Python\code\eg_cc1.py", line 17, in <module>
main()
File "D:\Programming\Python\code\eg_cc1.py", line 13, in main
im = Image.open(r.content)
NameError: global name 'Image' is not defined
I installed PIL in Lib\site-packages.
You need to explicitly import the Image module:
>>> from PIL import *
>>> Image
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Image' is not defined
>>> import PIL.Image
>>> Image
<module 'Image' from 'c:\Python27\lib\site-packages\PIL\Image.pyc'>
>>>
Or just
>>> import Image
Use
from PIL import Image
This way it will work, and your code will be forward-compatible with Pillow. On the other hand, import Image will not work with Pillow.
The development of PIL has been stopped in mid 2011, without any official announcement or explication. Pillow is a fork of original PIL and is actively developed.
If
import Image
is not working.
Try:
from PIL import Image
There is compatibility issue with all the packages in PIL. Try downloading PIL package manually for the latest version.
Actually worked with this in Python 3.2 Version, everything is working fine.
Related
I am using scikit-image to load a random image from a folder. OpenCV is being used for operations later on..
Code is as follows (only relevant parts included)
import imageio
import cv2 as cv
import fileinput
from collections import Counter
from data.apple_dataset import AppleDataset
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
from torchvision.models.detection.mask_rcnn import MaskRCNNPredictor
from torchvision.transforms import functional as F
import utility.utils as utils
import utility.transforms as T
from PIL import Image
import skimage.io
from skimage.viewer import ImageViewer
from matplotlib import pyplot as plt
%matplotlib inline
APPLE_IMAGE_PATH = r"__mypath__\samples\apples\images"
# Load a random image from the images folder
FILE_NAMES = next(os.walk(APPLE_IMAGE_PATH))[2]
random_apple_in_folder = os.path.join(APPLE_IMAGE_PATH, random.choice(FILE_NAMES))
apple_image = skimage.io.imread(random_apple_in_folder)
apple_image_cv = cv.imread(random_apple_in_folder)
apple_image_cv = cv.cvtColor(apple_image_cv, cv.COLOR_BGR2RGB)
Error is as follows
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-3-9575eed18f18> in <module>
11 FILE_NAMES = next(os.walk(APPLE_IMAGE_PATH))[2]
12 random_apple_in_folder = os.path.join(APPLE_IMAGE_PATH, random.choice(FILE_NAMES))
---> 13 apple_image = skimage.io.imread(random_apple_in_folder)
14 apple_image_cv = cv.imread(random_apple_in_folder)
AttributeError: 'PngImageFile' object has no attribute '_PngImageFile__frame'
How do i proceed from here? What should i change???
This is a bug in Pillow 7.1.0. You can upgrade Pillow with pip install -U pillow. See this bug report for more information:
https://github.com/scikit-image/scikit-image/issues/4548
I am trying to use the run_tesseract function to get an hocr output for extracting text from an image for Bank receipt images.However I am getting the above error message. I have installed Tesseract-OCR on my laptop, and have also added its path to my System Path variable.I have a windows 10 64 bit operating system,
I have tried uninstalling and reinstalling it also but to no avail.
import glob
import pytesseract
from PIL import Image
img_files=glob.glob('./NACH/*.jpg')
pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files\\Tesseract OCR\\tesseract.exe'
#im=Image.open(img_files[0])
#im.load()
pytesseract.run_tesseract(img_files[0],'output',lang='eng',config='hocr')
I get the following complete Error Message:
AttributeError Traceback (most recent call last)
in
4 im=Image.open(img_files[0])
5 im.load()
----> 6 pytesseract.run_tesseract(img_files[0],'output',lang='eng',config='hocr')
7 #text = pytesseract.image_to_string(im)
8 #if os.path.isfile('output.html'):AttributeError: module
'pytesseract' has no attribute 'run_tesseract'
Replace pytesseract.run_tesseract() with pytesseract.pytesseract.run_tesseract().
Credit Nithin in the comments. Adding this as an answer to close it out.
What I want to do:
I want to import a python module (pocketsphinx) and use the output from the Decoder attribute. However when I try to use it, I'm informed that module attribute 'Decoder' doesn't exist.
decoder = Decoder(configSwitches)
It does exist, though, which is what makes it so strange.
What I've done so far:
When I pull up a python console and input import pocketsphinx, it imports without any issue. Running pocketsphinx.file returns:
'/usr/local/lib/python2.7/dist-packages/pocketsphinx-0.0.8-py2.7-linux-armv7l.egg/pocketsphinx/__init__.pyc'
Looking in '/usr/local/lib/python2.7/dist-packages/pocketsphinx-0.0.8-py2.7-linux-armv7l.egg/pocketsphinx/__init__.py', I see: from pocketsphinx import * and that's it.
When I go back up to /usr/local/lib/python2.7/dist-packages/pocketsphinx/pocketsphinx.py and open it in a text editor, I see that pocketsphinx.py does indeed have a Decoder class with a healthy number of defined methods.
My Ask:
What other steps can I take to diagnose what's wrong with my use of the pocketsphinx module?
Here's the example code I was trying to run before really digging into the project:
import pocketsphinx
hmmd = r"/home/michael/Desktop/sphinxASR/pocketsphinx-5prealpha/model/en-us/en-us"
lmdir = r"/home/michael/Desktop/sphinxASR/pocketsphinx-5prealpha/model/en-us/en-us.lm.bin"
dictp = r"/home/michael/Desktop/sphinxASR/pocketsphinx-5prealpha/model/en-us/cmudict-en-us.dict"
fileName = r'/home/michael/Desktop/sphinxASR/voice_message.wav'
if __name__ == "__main__":
wavFile = open(fileName, "rb")
speechRec = pocketsphinx.Decoder(hmm=hmmd, lm=lmdir, dictionary=dictp)
wavFile.seek(44)
speechRec.decode_raw(wavFile)
result = speechRec.get_hyp()
print(result)
Stack trace:
Traceback (most recent call last):
File "/home/michael/PycharmProjects/27test/getHypTest.py", line 14, in <module>
speechRec = pocketsphinx.Decoder(lm=lmdir, dictionary=dictp)
AttributeError: 'module' object has no attribute 'Decoder'
By looking at the pocketsphinx example code, it seems that your import should be:
from pocketsphinx.pocketsphinx import *
My first step diagnosing this issue would be to type the following, so that I can see what is being imported:
import pocketsphinx
dir(pocketsphinx)
You should import Decoder from pocketsphinx.
Instead of
import pocketsphinx
try:
from pocketsphinx.pocketsphinx import Decoder
I have tried to work with the Tkinter library, however, I keep getting this message, and I don't know how to solve it.. I looked over the net but found nothing to this specific error - I call the library like this:
from Tkinter import *
and I get this error -
TclError = Tkinter.TclError
AttributeError: 'module' object has no attribute 'TclError'
I have no clue what can I do now..
Thank you
full traceback:
Traceback (most recent call last):
File "C:/Users/Shoham/Desktop/MathSolvingProject/Solver.py", line 3, in <module>
from Tkinter import *
File "C:\Heights\PortableApps\PortablePython2.7.6.1\App\lib\lib- tk\Tkinter.py", line 41, in <module>
TclError = Tkinter.TclError
AttributeError: 'module' object has no attribute 'TclError'
You imported (mostly) everything from the module with from Tkinter import *. That means that (mostly) everything in that module is now included in the global namespace, and you no longer have to include the module name when you refer to things from it. Thus, refer to Tkinter's TclError object as simply TclError instead of Tkinter.TclError.
The problem seems to be in "C:\Heights\PortableApps\PortablePython2.7.6.1\App\lib\lib-tk\Tkinter.py:
The regular python install imports in lib-tk\Tkinter.py are different to what is in PortablePython2.7.6.1\App\lib\lib-tk\Tkinter.py:
try:
import _tkinter
except ImportError, msg:
raise ImportError, str(msg) + ', please install the python-tk package'
tkinter = _tkinter # b/w compat for export
TclError = _tkinter.TclError
Then where Tkinter is used in PortablePython _tkinter is used instead. It seems like a bug in PortablePython.
The full contents of the file are here. Replacing the file in C:\Heights\PortableApps\PortablePython2.7.6.1\App\lib\lib-tk\Tkinter.py as per the comments fixes the issue.
Like #ErezProductions said. You either have to import everything and access it directly or import only the module.
from Tkinter import *
TclError
or
import Tkinter
Tkinter.TclError
See the difference:
>>> import tkinter
>>> TclError = tkinter.TclError
>>>
No error. But, with your method:
>>> from tkinter import *
>>> TclError = tkinter.TclError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'tkinter' is not defined
The difference is that the first method imports the module tkinter into the name space. You can address its properties using the dot notation tinter.property. However, the from tkinter import * imports the module's properties into the name space, not the module itself.
Either try the first method given above, or adjust your approach (NB: importing all properties is a bad idea) like so:
>>> from tkinter import *
>>> my_TclError = TclError # renamed because TclError defined in tkinter
>>>
So, I've followed this question in order to get some sound playing with Music21, and here's the code:
from music21 import *
import random
def main():
# Set up a detuned piano
# (where each key has a random
# but consistent detuning from 30 cents flat to sharp)
# and play a Bach Chorale on it in real time.
keyDetune = []
for i in range(0, 127):
keyDetune.append(random.randint(-30, 30))
b = corpus.parse('bach/bwv66.6')
for n in b.flat.notes:
n.microtone = keyDetune[n.midi]
sp = midi.realtime.StreamPlayer(b)
sp.play()
return 0
if __name__ == '__main__':
main()
And here's the traceback:
Traceback (most recent call last):
File "main.py", line 49, in <module>
main()
File "main.py", line 44, in main
sp.play()
File "G:\Development\Python Development\Anaconda3\lib\site-packages\music21\mi
di\realtime.py", line 104, in play
streamStringIOFile = self.getStringIOFile()
File "G:\Development\Python Development\Anaconda3\lib\site-packages\music21\mi
di\realtime.py", line 110, in getStringIOFile
return stringIOModule.StringIO(streamMidiWritten)
AttributeError: type object '_io.StringIO' has no attribute 'StringIO'
Press any key to continue . . .
I'm running Python 3.4 x86 (Anaconda Distribution) on Windows 7 x64. I have no idea on how to fix this (But probably is some obscure Python 2.x to Python 3.x incompatibility issue, as always)
EDIT:
I've edited the import as suggested in the answer, and now I got a TypeError:
What would you recommend me to do as an alternative to "play some audio" with Music21? (Fluidsynth or whatever, anything).
You may be right... I think the error may actually be in Music21, with the way it handles importing StringIO
Python 2 has StringIO.StringIO, whereas
Python 3 has io.StringIO
..but if you look at the import statement in music21\midi\realtime.py
try:
import cStringIO as stringIOModule
except ImportError:
try:
import StringIO as stringIOModule
except ImportError:
from io import StringIO as stringIOModule
The last line is importing io.StringIO, and so later on the call to stringIOModule.StringIO() fails because it's actually calling io.StringIO.StringIO.
I would try to edit the import statement to:
except ImportError:
import io as stringIOModule
And see if that fixes it.
return stringIOModule.StringIO(streamMidiWritten)
AttributeError: type object '_io.StringIO' has no attribute 'StringIO'
Press any key to continue . . .
Please #Ericsson, just remove the StringIO from the return value and you are good to go.
It will now be:
return stringIOModule(streamMidiWritten)