Image conversion in PIL, pgm file error - python

When trying to do the following in the PIL python library:
Image.open('Apple.gif').save('Apple.pgm')
the code fails with:
Traceback (most recent call last):
File "/home/eran/.eclipse/org.eclipse.platform_3.7.0_155965261/plugins/org.python.pydev_2.6.0.2012062818/pysrc/pydevd_comm.py", line 765, in doIt
result = pydevd_vars.evaluateExpression(self.thread_id, self.frame_id, self.expression, self.doExec)
File "/home/eran/.eclipse/org.eclipse.platform_3.7.0_155965261/plugins/org.python.pydev_2.6.0.2012062818/pysrc/pydevd_vars.py", line 376, in evaluateExpression
result = eval(compiled, updated_globals, frame.f_locals)
File "<string>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1439, in save
save_handler(self, fp, filename)
File "/usr/lib/python2.7/dist-packages/PIL/PpmImagePlugin.py", line 114, in _save
raise IOError, "cannot write mode %s as PPM" % im.mode
IOError: cannot write mode P as PPM
The code works fine with conversion to BMP, but JPG also fails.
Strange thing is, a different file(JPG to PGM), works ok.
Other format conversion. That is:
Image.open('Apple.gif').save('Apple.bmp')
works.
Any idea why?

You need to convert the image to RGB mode to make this work.
im = Image.open('Apple.gif')
im = im.convert('RGB')
im.save('Apple.pgm')

Related

Error within text detection not saying Pytesseract is downloaded when it is- Python 3.9

Python 3.9, Pycharm
Am trying to run this code to use the live webcam to take a screenshot, than process that screenshot and identify any text in the screenshot
Code I have put in:
import cv2
from PilLite import Image
import pytesseract
camera=cv2.VideoCapture(0)
def NIC_tesseract():
path_to_tesseract=r"Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pytesseract"
pytesseract.pytesseract.tesseract_cmd=path_to_tesseract
#Imagepath='test1.jpg'
pytesseract.tesseract_cmd=path_to_tesseract
text=print(pytesseract.image_to_string(Image.open('test1.jpg'),lang="eng"))
print(text[:-1])
while True:
_,PicturePhoto=camera.read()
cv2.imshow('Text Detection',PicturePhoto)
if cv2.waitKey(30)& 0xFF==ord('s'):
cv2.imwrite('test1.jpg',PicturePhoto)
break
camera.release()
cv2.destroyAllWindows()
NIC_tesseract()
Error Coming Up:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pytesseract/pytesseract.py", line 254, in run_tesseract
proc = subprocess.Popen(cmd_args, **subprocess_args())
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/subprocess.py", line 947, in init
self._execute_child(args, executable, preexec_fn, close_fds,
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/subprocess.py", line 1819, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pytesseract'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/NicAveray/PycharmProjects/FacialRecognition/Trial 2.py", line 25, in
NIC_tesseract()
File "/Users/NicAveray/PycharmProjects/FacialRecognition/Trial 2.py", line 13, in NIC_tesseract
text = pytesseract.image_to_string(PicturePhoto, lang="eng")
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pytesseract/pytesseract.py", line 416, in image_to_string
return {
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pytesseract/pytesseract.py", line 419, in
Output.STRING: lambda: run_and_get_output(*args),
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pytesseract/pytesseract.py", line 286, in run_and_get_output
run_tesseract(**kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pytesseract/pytesseract.py", line 258, in run_tesseract
raise TesseractNotFoundError()
pytesseract.pytesseract.TesseractNotFoundError: Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pytesseract is not installed or it's not in your PATH. See README file for more information.
You assign 'Image' the return from camera.read() while at the same time it is a function imported from PilLite. I think the return from camera.read() is actually a numpy array, which explains the error message. Change the variable name of the return I would suggest.
I'm not sure why you added a print in the line of the OCR. However, please try passing the full path directly.
text = pytesseract.image_to_string(r"D:/.../test1.jpg", lang="eng")
I'm just worried that the time taken to write the image and reading it is too much, so you should read the frames directly by passing your variable "PicturePhoto" to tesseract like this:
text = pytesseract.image_to_string(PicturePhoto, lang="eng")

read_mrz error : Could not find a format to read the specified file in mode 'i'

The below code is what i am using to read mrz data from a passport, and it works absolutely fine when i run it on my local computer, but when i try to execute it on my server (Windows AWS server) it throws an error.
Can you please help what's this error and how to resolve it.
from PIL import Image
import sys
from passporteye import read_mrz
import pytesseract
mrz = read_mrz("C:/docs/IMG/PASSPORT/abc.png")
Error :
Traceback (most recent call last):
File "C:/qfc_apps/edocs/PY/PASSPORT/passport.py", line 64, in <module>
passport()
File "C:/qfc_apps/edocs/PY/PASSPORT/passport.py", line 19, in passport
mrz = read_mrz("C:/docs/IMG/PASSPORT/abc.png")
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\passporteye\mrz\image.py", line 337, in read_mrz
mrz = p.result
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\passporteye\mrz\image.py", line 325, in result
return self['mrz_final']
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\passporteye\util\pipeline.py", line 102, in __getitem__
self._compute(key)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\passporteye\util\pipeline.py", line 109, in _compute
self._compute(d)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\passporteye\util\pipeline.py", line 109, in _compute
self._compute(d)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\passporteye\util\pipeline.py", line 109, in _compute
self._compute(d)
[Previous line repeated 1 more times]
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\passporteye\util\pipeline.py", line 111, in _compute
results = self.components[cname](*inputs)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\passporteye\mrz\image.py", line 52, in __call__
return self._imread(self.file)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\passporteye\mrz\image.py", line 37, in _imread
img = skimage_io.imread(file, as_gray=self.as_gray, plugin='imageio')
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\skimage\io\_io.py", line 61, in imread
img = call_plugin('imread', fname, plugin=plugin, **plugin_args)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\skimage\io\manage_plugins.py", line 210, in call_plugin
return func(*args, **kwargs)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\imageio\core\functions.py", line 221, in imread
reader = read(uri, format, "i", **kwargs)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\imageio\core\functions.py", line 139, in get_reader
"Could not find a format to read the specified file " "in mode %r" % mode
ValueError: Could not find a format to read the specified file in mode 'i'
Figured out the solution after hours of research so posting my solution for others who might face a similar solution.
I still couldnt figure out what was the problem with the above code but i managed a way out.
Documentation of passporteye mentions that either we pass the path of the image or a byte stream containing image data. As path was not working for me so i opted for the second method.
Using the below code solves our problem :-
image = cv2.imread("path of image")
import PIL.Image as Image
import io
pil_im = Image.fromarray(image)
b = io.BytesIO()
pil_im.save(b, 'jpeg')
im_bytes = b.getvalue()
mrz = read_mrz(im_bytes)

unable to perform OCR using python

I am trying to build a a python program to recognize the text from text containing objects in realtime. I was able to do OCR using tesseract from command line just to check if it works for static images or not. However, to use this in python we have to get use of pytesseract wrapper to use tesseract in python. I am following this Tutorial. But when i execute the script from the tutorial with sample image, it throws error like this:
Traceback (most recent call last):
File "C:\Python27\tess1.py", line 4, in <module>
print(pytesseract.image_to_string(Image.open('example_01.png')))
File "build\bdist.win-amd64\egg\pytesseract\pytesseract.py", line 193, in
image_to_string
return run_and_get_output(image, 'txt', lang, config, nice)
File "build\bdist.win-amd64\egg\pytesseract\pytesseract.py", line 130, in
run_and_get_output
temp_name, img_extension = save_image(image)
File "build\bdist.win-amd64\egg\pytesseract\pytesseract.py", line 86, in
save_image
image.save(input_file_name, format=img_extension, **image.info)
File "C:\Python27\lib\site-packages\PIL\Image.py", line 1420, in save
self.load()
File "C:\Python27\lib\site-packages\PIL\ImageFile.py", line 193, in load
d = Image._getdecoder(self.mode, d, a, self.decoderconfig)
File "C:\Python27\lib\site-packages\PIL\Image.py", line 356, in
_getdecoder
raise IOError("decoder %s not available" % decoder_name)
IOError: decoder zip not available

OSError when reading image files using matplotlib

When trying to follow the example posted here. The code segment is the same as given in the example
import matplotlib.image as mpimg
filename = "/home/MarshOrchid.jpg"
image = mpimg.imread(filename)
# Print out its shape
print(image.shape)
Running the code gives the following error message. What could be the underlying cause?
Traceback (most recent call last):
File "test2.py", line 5, in <module>
image = mpimg.imread(filename)
File "/tfw/lib/python3.4/site-packages/matplotlib-1.5.1-py3.4-linux- x86_64.egg/matplotlib/image.py", line 1304, in imread
im = pilread(fname)
File "/tfw/lib/python3.4/site-packages/matplotlib-1.5.1-py3.4-linux-x86_64.egg/matplotlib/image.py", line 1283, in pilread
return pil_to_array(image)
File "/tfw/lib/python3.4/site-packages/matplotlib-1.5.1-py3.4-linux-x86_64.egg/matplotlib/image.py", line 1400, in pil_to_array
x = toarray(im)
File "/tfw/lib/python3.4/site-packages/matplotlib-1.5.1-py3.4-linux-x86_64.egg/matplotlib/image.py", line 1383, in toarray
x_str = im.tobytes('raw', im.mode)
File "/tfw/lib/python3.4/site-packages/Pillow-3.2.0-py3.4-linux-x86_64.egg/PIL/Image.py", line 678, in tobytes
File "/tfw/lib/python3.4/site-packages/Pillow-3.2.0-py3.4-linux-x86_64.egg/PIL/ImageFile.py", line 235, in load
File "/tfw/lib/python3.4/site-packages/Pillow-3.2.0-py3.4-linux-x86_64.egg/PIL/ImageFile.py", line 59, in raise_ioerror
OSError: broken data stream when reading image file

Python Scipy library: saving images

I am learning image processing with scipy. I experience some diffuculties with rather basic opeartions as saving an image. Here is my code:
import scipy
from scipy import misc
img=misc.imread("C:\\..\\name.jpg")
misc.imsave("image.jpg",img)
I obtain error message:
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
misc.imsave("image.jpg",img)
File "C:\Python27\lib\site-packages\scipy\misc\pilutil.py", line 158, in imsave
im.save(name)
File "C:\Python27\lib\site-packages\PIL\Image.py", line 1461, in save
fp = builtins.open(fp, "wb")
IOError: [Errno 13] Permission denied: 'image.jpg'
Try to use the full path when saving:
misc.imsave(r'C:\path\image.jpg', img)
your error is a permission error, so probably you do not have access to write in the current directory. You can also change the current directory using os.chdir( newpath ).
The code above creates a file in a given directory but it is empty (0 bytes) and produces error in the IDLE:
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
misc.imsave(r"D:\Darek\back3.jpg", img)
File "C:\Python27\lib\site-packages\scipy\misc\pilutil.py", line 158, in imsave
im.save(name)
File "C:\Python27\lib\site-packages\PIL\Image.py", line 1467, in save
save_handler(self, fp, filename)
File "C:\Python27\lib\site-packages\PIL\JpegImagePlugin.py", line 557, in _save
ImageFile._save(im, fp, [("jpeg", (0,0)+im.size, 0, rawmode)])
File "C:\Python27\lib\site-packages\PIL\ImageFile.py", line 466, in _save
e = Image._getencoder(im.mode, e, a, im.encoderconfig)
File "C:\Python27\lib\site-packages\PIL\Image.py", line 395, in _getencoder
return encoder(mode, *args + extra)
TypeError: function takes at most 11 arguments (13 given)
Hmm, your code works fine for me in the dreampie shell
import scipy
from scipy import misc
img = misc.imread("C:/folder/name.jpg")
misc.imsave("C:/folder2/image.jpg",img)
I don't know PIL well enough, but there seems to be an encoder issue involved. Have you tried your code with different image files?

Categories