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)
Related
I am trying create a list of image file names, sorted by the size of the file:
path = '/home/onur/Desktop/dataset/'
images = sorted(os.listdir(path), key = os.path.getsize)
print(images)
But I'm getting this error:
Traceback (most recent call last):
File "/home/onur/Desktop/image-downloader.py", line 98, in <module>
images = sorted(os.listdir(path), key = os.path.getsize)
File "/usr/lib/python3.9/genericpath.py", line 50, in getsize
return os.stat(filename).st_size
FileNotFoundError: [Errno 2] No such file or directory: 'image_535.jpg'
The python file is NOT in /home/onur/Desktop/dataset/. It is just in Desktop so I wonder if that is the reason for the error. If so, how can I fix it?
You are correct. The problem is that os.path.getsize raises an error if the file does not exist. Because your Python script is in /home/onur/Desktop and the file name passed to os.path.getsize is just image_535.jpg, os.path.getsize looks for the file in your Desktop directory. Since the file is not there, os.path.getsize raises the error. You could run this to correctly test the file size.
path = '/home/onur/Desktop/dataset/'
images = sorted(os.listdir(path), key=lambda f: os.path.getsize(os.path.join(path, f)))
print(images)
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'
I am using this code (answer by #user2019716) to convert .tif to .jpeg to use on the tensorflow object detection API. I have done the conversion before with no problems, but for some reason today, I receive a No such file or directory: '__0.tif' error and I don't understand why this is happening. I've checked the directory that I put in C:/Users/name/Desktop/phantom80_labelImg/TIF/ and there are a list of .tif files starting from __0.tif to __34.tif. I know the code works because I have used it before, but I don't know why it is not reading file .tif files now.
Any suggestions?
import os
from PIL import Image
for infile in os.listdir("C:/Users/name/Desktop/phantom80_labelImg/TIF/"):
print("file : " + infile)
if infile[-3:] == "tif" or infile[-3:] == "bmp" :
# print "is tif or bmp"
outfile = infile[:-3] + "jpeg"
im = Image.open(infile)
print("new filename : " + outfile)
out = im.convert("RGB")
out.save(outfile, "JPEG", quality=90)
C:\Users\name\anaconda3\envs\MaskRCNN_SpeCraft\python.exe C:/Users/name/z/MaskRCNN_SpeCraft/tif_to_jpeg.py
Traceback (most recent call last):
File "C:/Users/name/z/MaskRCNN_SpeCraft/tif_to_jpeg.py", line 12, in <module>
im = Image.open(infile)
File "C:\Users\name\anaconda3\envs\MaskRCNN_SpeCraft\lib\site-packages\PIL\Image.py", line 2891, in open
fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: '__0.tif'
C:\Users\name\z\MaskRCNN_SpeCraft
file : __0.tif
Process finished with exit code 1
os.listdir(dir) only returns names of the files in that directory (documentation).
To open file you will need to get full file path. You can use os.path.join (documentation)
root_dir = "C:/Users/name/Desktop/phantom80_labelImg/TIF/"
for filename in os.lisdir(root_dir):
infile = os.path.join(root_dir, filename)
# rest of your code
I am trying to create an array of .jpg files, but the compiler is not building the array
More specifically, my problem is that a public folder, whose path is defined as the object path, is not accessible by my Python compiler [Spyder]. However, the folder, and its respective files are all public and open access to everyone. What might be the reason that my computer cannot access the images?
Code 1 is an simple function to find and access the file path I want, and the Kernal results show what is failing.
Code 2 is the syntax for the isolated error in the program I am applying the open() method. Kernal results depict compiler failure.
Code 1:
import os
path = r'C:/Users/BeckerLab/Pictures/Final_Sample_Set/Right2'
try:
os.path.exists(path)
if (True):
R = open(path)
R.close()
except FileNotFoundError:
print("file does not exist")
Kernal for Code 1:
!runfile('C:/Users/BeckerLab/untitled6.py', wdir='C:/Users/BeckerLab')
Traceback (most recent call last):
File "C:\Users\BeckerLab\untitled6.py", line 8, in <module>
R = open(path)
PermissionError: [Errno 13] Permission denied: 'C:/Users/BeckerLab/Pictures/Final_Sample_Set/Right2'
Code 2:
import os
rightSamples = [open(file, 'r+') for file in os.listdir(r'C:/Users/Public/Right2')]
Kernal Results for Code 2:
!runfile('C:/Users/BeckerLab/almost.py', wdir='C:/Users/BeckerLab')
2020-04-05 12:59:28
Traceback (most recent call last):
File "C:\Users\BeckerLab\almost.py", line 46, in <module>
rightSamples = [open(file, 'r+') for file in os.listdir(r'C:/Users/Public/Right2')]
File "C:\Users\BeckerLab\almost.py", line 46, in <listcomp>
rightSamples = [open(file, 'r+') for file in os.listdir(r'C:/Users/Public/Right2')]
FileNotFoundError: [Errno 2] No such file or directory: 'R1.JPG'
Notice that your condition is:
os.path.exists(path)
if (True):
which will always be true. Maybe try:
if (os.path.exists(path)):
Try moving the files to another directory like 'D:/../BeckerLab/untitled6.py'
So, I've got PIL installed (at least I think properly) to convert color images to grayscale, and when I use this code
from PIL import Image
image_file = Image.open("James.png") # open colour image
image_file = image_file.convert('1') # convert image to black and white
image_file.save('Gray.png')
IDLE shows me this...
Traceback (most recent call last):
File "C:/Users/Kane/Desktop/huh.py", line 2, in <module>
image_file = Image.open("James.png")
File "C:\Python27\lib\site-packages\PIL\Image.py", line 1952, in open
fp = __builtin__.open(fp, "rb")
IOError: [Errno 2] No such file or directory: 'James.png'
What do I need to do to fix this? I have Python 2.7, does this make a difference?
Your problem could be that the image file "James.png" is not in the same directory as your script, in your example on your Desktop. Is that the case?
Cheers