The file evidently exists, but imread() is unable to identify the image. Is there something I am missing? I'm still new to python and its respective libraries.
Code (Python 3.7.9)
import os
import time
import numpy as np
import matplotlib.pyplot as plt
from randomlyShiftChannels import *
from alignChannels import *
from utils import *
#Path to your data directory
data_dir = os.path.join('..', 'data', 'demosaic')
#List of images
image_names = ['balloon.jpeg','cat.jpg', 'ip.jpg',
'puppy.jpg', 'squirrel.jpg', 'pencils.jpg',
'house.png', 'light.png', 'sails.png', 'tree.jpeg'];
print('Evaluating alignment...')
for imgname in image_names:
# Read image
imgpath = os.path.join(data_dir, imgname)
print("File exists:", os.path.exists(imgpath))
img = imread(imgpath)
Output
File exists: True
Traceback (most recent call last):
File "D:\Spring2021\CS370\week 6\p2-release\code\evalAlignment.py", line 48, in <module>
img = imread(imgpath)
File "D:\Spring2021\CS370\week 6\p2-release\code\utils.py", line 14, in imread
img = plt.imread(path).astype(float)
File "C:\Users\dminn\AppData\Local\Programs\Spyder\pkgs\matplotlib\pyplot.py", line 2246, in imread
return matplotlib.image.imread(fname, format)
File "C:\Users\dminn\AppData\Local\Programs\Spyder\pkgs\matplotlib\image.py", line 1496, in imread
with img_open(fname) as image:
File "C:\Users\dminn\AppData\Local\Programs\Spyder\pkgs\PIL\Image.py", line 2944, in open
"cannot identify image file %r" % (filename if filename else fp)
UnidentifiedImageError: cannot identify image file '..\\data\\demosaic\\balloon.jpeg'
I faced the identical issue using Spyder (Spyder 5.0.0 and 5.0.1).
No errors appeared when running the script from the command line.
Found workaround for Spyder: use pil_to_array() instead of imread()
from PIL import Image
img = pil_to_array(Image.open(imgpath))
Try converting your path to an absolute path, there are reasons we call it good practice
Sample code:
import os
os.path.abspath("mydir/myfile.txt") #'C:/example/cwd/mydir/myfile.txt'
Related
This is my code. Basically i want to load all images in a folder inside my D drive in a loop.
from PIL import Image
def loadimages(path):
list=listdir(path)
loadedimages=[]
for image in list:
img=Image.open(path+image)
loadedimages.append(img)
return loadedimages
path= r"D:\ACADEMICS\8SEM\PatternClassification\CBT-1\TrainCharacters"
imgs=loadimages(path)
I am getting error like this
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
imgs=loadimages(path)
File "<pyshell#11>", line 5, in loadimages
img=Image.open(path+image)
File "C:\Users\anjana ouseph\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\Image.py", line 2809, in open
fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'D:\\ACADEMICS\\8SEM\\PatternClassification\\CBT-1\\TrainCharacters1'
If the images are inside the TrainCharacters folder, you are missing a "\"
currently its looking for
'D:\\ACADEMICS\\8SEM\\PatternClassification\\CBT-1\\TrainCharacters1'
It's likely you need
'D:\\ACADEMICS\\8SEM\\PatternClassification\\CBT-1\\TrainCharacters\\1'
It appears the problem is the line img=Image.open(path+image).
I would recommend using the built-in Python path manipulation method os.path.join:
from PIL import Image
import os
def loadimages(path):
list=listdir(path)
loadedimages=[]
for image in list:
img=Image.open(os.path.join(path, image))
loadedimages.append(img)
return loadedimages
path= r"D:\ACADEMICS\8SEM\PatternClassification\CBT-1\TrainCharacters"
imgs=loadimages(path)
#!/usr/bin/python
from PIL import Image
import os, sys
path = "C:/Users/nonono/Desktop/hypergan/data/trainingData/"
dirs = os.listdir( path )
def resize():
for item in dirs:
if os.path.isfile(path+item):
im = Image.open(path+item)
f, e = os.path.splitext(path+item)
imResize = im.resize((256,256), Image.ANTIALIAS)
imResize.save(f + ' resized.jpg', 'JPEG', quality=90)
resize()
i got this code from another answer here and fitted it to my own parameters, yet when i run it in the command line i get an error:
Traceback (most recent call last):
File "resize.py", line 16, in <module>
resize()
File "resize.py", line 11, in resize
im = Image.open(path+item)
File "C:\Users\nonono\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\Image.py", line 2822, in open
raise IOError("cannot identify image file %r" % (filename if filename else fp))
OSError: cannot identify image file 'C:/Users/nonono/Desktop/hypergan/data/trainingData/bx71zze7egy18wel231 resized.jpg'
the folder trainingData is filled with a large amount of images, that i want to resize to 256x256 regardless of aspect ratio, i will not need the images afterwards so if there is a way to replace the images instead of just copying, resizing, and renaming, that would be great (unless i am reading this incorrectly, i have about 2 weeks experience in python)
any help would be appreciated
I want use PIL .save() method for export my PIL image list to pdf.
in the PIL document , saving part say:
=> we can use append_images option for pdf format.
and in pillow's github page , this issue say : Added append_images to PDF saving #2526
I wrote this code:
import PIL
im1 = PIL.Image.open("1.jpg").convert("RGB")
im2 = PIL.Image.open("2.jpg").convert("RGB")
im3 = PIL.Image.open("3.jpg").convert("RGB")
images = [im1,im2,im3]
images[0].save("out.pdf", save_all=True, append_images=images[1:])
but it doesn't work!
These errors raised:
Traceback (most recent call last):
File "sample.py", line 13, in <module>
gif.save("out.pdf", save_all=True, append_images=images)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/PIL/Image.py", line 1928, in save
save_handler(self, fp, filename)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/PIL/PdfImagePlugin.py", line 55, in _save_all
_save(im, fp, filename, save_all=True)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/PIL/PdfImagePlugin.py", line 182, in _save
Image.SAVE["JPEG"](im, op, filename)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/PIL/JpegImagePlugin.py", line 609, in _save
info = im.encoderinfo
AttributeError: 'Image' object has no attribute 'encoderinfo'
Try this format
from PIL import Image
im1 = PIL.Image.open("1.jpg").convert("RGB")
im2 = PIL.Image.open("2.jpg").convert("RGB")
im3 = PIL.Image.open("3.jpg").convert("RGB")
images = [im2,im3]
im1.save("out.pdf", save_all=True, append_images=images)
This problem is solved in PIL ver 5.0.0 (https://pillow.readthedocs.io/en/latest/).
Somewhat off topic, but if you have a large number of images to convert, using list comprehension is the way to go.
from PIL import Image
im1=Image.open('1.png').convert('RGB')
images = [Image.open(f”{imgNumber}.png”).convert('RGB') for imgNumber in range(2, 100)]
im1.save("imgBook.PDF", save_all=True, append_images=images)
hi i'm working in an app which generate barcodes into a pdf file. I tried it in linux and worked perfectly, but when try it in Windows, i receive some errors.
My code is the next:
def crear_barcode(numero):
filename = 'generated/temp/'+numero
writer = barcode.writer.ImageWriter()
code = barcode.Code39(numero,writer,add_checksum = False)
archivo = code.save(filename)
return archivo
and the errors I receiving are that:
Traceback (most recent call last):
File "C:\Documents and Settings\usuario\Escritorio\NIF-master\nif.py", line 23, in generarButton_clicked
generar_codigos(provincia,ciudad,numeroInicial,cantidad)
File "C:\Documents and Settings\usuario\Escritorio\NIF-master\controller\controller.py", line 64, in generar_codigos
archivo.image(crear_barcode(numero),eje_x * 50, linea * 25 , TAMANIO_CODIGO)
File "C:\Documents and Settings\usuario\Escritorio\NIF-master\controller\controller.py", line 43, in crear_barcode
archivo = code.save(filename)
File "C:\Python27\lib\site-packages\pybarcode-0.7-py2.7.egg\barcode\base.py", line 69, in save
_filename = self.writer.save(filename, output)
File "C:\Python27\lib\site-packages\pybarcode-0.7-py2.7.egg\barcode\writer.py", line 291, in save
output.save(filename, self.format.upper())
File "C:\Python27\lib\site-packages\PIL\Image.py", line 1681, in save
save_handler = SAVE[format.upper()]
KeyError: u'PNG'
when I change the save() line and give it an extension ie:
code.save(filename,'png')
I receive that
Traceback (most recent call last):
File "C:\Documents and Settings\usuario\Escritorio\NIF-master\nif.py", line 23, in generarButton_clicked
generar_codigos(provincia,ciudad,numeroInicial,cantidad)
File "C:\Documents and Settings\usuario\Escritorio\NIF-master\controller\controller.py", line 64, in generar_codigos
archivo.image(crear_barcode(numero),eje_x * 50, linea * 25 , TAMANIO_CODIGO)
File "C:\Documents and Settings\usuario\Escritorio\NIF-master\controller\controller.py", line 43, in crear_barcode
archivo = code.save(filename,'png')
File "C:\Python27\lib\site-packages\pybarcode-0.7-py2.7.egg\barcode\base.py", line 68, in save
output = self.render(options)
File "C:\Python27\lib\site-packages\pybarcode-0.7-py2.7.egg\barcode\codex.py", line 105, in render
options.update(writer_options or {})
ValueError: dictionary update sequence element #0 has length 1; 2 is required
I don't understand why occur in windows and not in linux.
I have installed all the dependencies, PIL, pyBarcode, pyFpdf.
I faced a similar issue earlier, and this is what I did to solved it :
1) Open this file - C:\Python27\lib\site-packages\pybarcode-0.7-py2.7.egg\barcode\writer.py
2) You will see the following code -
try:
import Image, ImageDraw, ImageFont ### The Statement to be edited ####
except ImportError:
try:
from PIL import Image, ImageDraw, ImageFont # lint:ok
except ImportError:
import sys
sys.stderr.write('PIL not found. Image output disabled.\n\n')
Image = ImageDraw = ImageFont = None # lint:ok
3) You need to edit the first import statement to make the code look like the following -
try:
from PIL import Image, ImageDraw, ImageFont ### Edited.
except ImportError:
try:
from PIL import Image, ImageDraw, ImageFont # lint:ok
except ImportError:
import sys
sys.stderr.write('PIL not found. Image output disabled.\n\n')
Image = ImageDraw = ImageFont = None # lint:ok
4) Save the file.
5) Try running your app.
I hope this helps.
Without having the full code to test, it looks like this is due to OS specific file separators. Linux uses forward slashes vs. Windows uses backslashes. Try using platform independent filenames:
filename = os.path.join('generated','temp', str(numero))
I am using only PIL then it's work properly when I use pytesser then it doesn't work properly .What can i do for it?
from PIL import Image
from pytesser import *
image_file = Image.open("vote.jpg")
im = Image.open(image_file)
text = image_to_string(im)
print text
Traceback (most recent call last):
File "C:/Users/Tanvir/Desktop/py thon hand/hala.py", line 4, in <module>
image_file = Image.open("vote.jpg")
File "C:\Pythons27\lib\site-packages\PIL\Image.py", line 2286, in open
% (filename if filename else fp))
IOError: cannot identify image file 'vote.jpg'
I am find this solution .It was problem with PIL so at first I have to uninstall this PIL module then again install it and job done Every thing is okay.