fp = builtins.open(filename, "rb") - Error - python

When I try running this script:
from PIL import Image
import os
files = os.listdir('mri')
for file in files:
img = Image.open(file)
I get the following error:
Traceback (most recent call last):
File "resize_image.py", line 6, in <module>
img = Image.open(file)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 2258, in open
fp = builtins.open(filename, "rb")
IOError: [Errno 2] No such file or directory: '6.jpg'
I made sure that 6.jpg is available. And, it seems that I get such error for any image in this location.
How can I fix the issue?
Thanks.

The file names from os.listdir are relative to the directory given. They must be made complete by joining the dirname to their basename.
files = os.listdir('my_folder')
for file in files:
img = Image.open(os.path.join('my_folder', file))

You are getting this error because you haven't add your image in project file folder.
Paste your image in project file and then run the program.

img = Image.open(os.path.join('mri', file))
this worked for me making sure you join the dir with the path

img = Image.open(os.path.join(r'C:\Users\Simin\Desktop\python proj\img.jpg'))
this direct path worked for me

Related

Unable to open or read log files: FileNotFoundError [duplicate]

I'm trying to run the following script which simply reads and image and saves it again:
from PIL import Image
import os
rootdir = '/home/user/Desktop/sample'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
im = Image.open(file)
im.save(file)
I however get the following error:
Traceback (most recent call last):
File "test.py", line 10, in <module>
im = Image.open(file)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 2258, in open
fp = builtins.open(filename, "rb")
IOError: [Errno 2] No such file or directory: '1.jpg'
So, what I'm trying to do is simply read the file 1.jpg and save it again, provided that 1.jpg is located in the directory.
How can I fix this issue?
Thanks.
You're going to need to provide a fully qualified path, because file holds only the tail, not the entire path.
You can use os.path.join to join the root to the tail:
for root, dirs, files in os.walk(rootdir):
for file in files:
path = os.path.join(root, file)
im = Image.open(path)
im.save(path)

Running image conversion script gives me "no such file"

I have this image conversion script written in Python. I have some images in a folder that go like turbo1, turbo2, and so on...
I need to convert them from png to jpeg.
This is my code:
from PIL import Image
import os
directory = r'C:\Users\Filip\Desktop\turbos'
c=1
for filename in os.listdir(directory):
if filename.endswith(".PNG"):
im = Image.open(filename)
name='turbo'+str(c)+'.jpeg'
rgb_im = im.convert('RGB')
rgb_im.save(name)
c+=1
print(os.path.join(directory, filename))
continue
else:
continue
I get this error:
Traceback (most recent call last):
File "c:\Users\Filip\Desktop\convert.py", line 9, in <module>
im = Image.open(filename)
File "C:\Python\lib\site-packages\PIL\Image.py", line 2953, in open
fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'turbo1.PNG'
If I change filename.endswith(".PNG"): to filename.endswith(".png"):
it does not give me that error but the images don't convert.
What am I missing here?
.png and .PNG. are two different file extensions and your code should be
im = Image.open(os.path.join(directory, filename))

Why does do I have an IO error saying my file doesn't exist even though it does exist in the directory?

I am trying to loop over a Python directory, and I have a specific file that happens to be the last file in the directory such that I get an IOerror for that specific file.
The error I get is:
IOError: [Errno 2] No such file or directory: 'nod_gyro_instance_11_P_4.csv'
My script:
for filename in os.listdir("/Users/my_name/PycharmProjects/My_Project/Data/Nod/Gyro"):
data = []
if filename.endswith(".csv"):
data.append(k_fold(filename))
continue
else:
continue
k_fold does this:
def k_fold(myfile, myseed=11109, k=20):
# Load data
data = open(myfile).readlines()
The entire traceback:
Traceback (most recent call last):
File "/Users/my_name/PycharmProjects/MY_Project/Cross_validation.py", line 30, in <module>
data.append(k_fold(filename))
File "/Users/my_name/PycharmProjects/My_Project/Cross_validation.py", line 8, in k_fold
data = open(myfile).readlines()
IOError: [Errno 2] No such file or directory: 'nod_gyro_instance_11_P_4.csv'
My CSV files are such:
nod_gyro_instance_0_P_4.csv
nod_gyro_instance_0_P_3.csv
nod_gyro_instance_0_P_2.csv
nod_gyro_instance_0_P_5.csv
...
nod_gyro_instance_11_P_4.csv
nod_gyro_instance_10_P_6.csv
nod_gyro_instance_10_P_5.csv
nod_gyro_instance_10_P_4.csv
Why doesn't it recognize my nod_gyro_instance_10_P_4.csv file?
os.listdir returns just filenames, not absolute paths. If you're not currently in that same directory, trying to read the file will fail.
You need to join the dirname onto the filename returned:
data_dir = "/Users/my_name/PycharmProjects/My_Project/Data/Nod/Gyro"
for filename in os.listdir(data_dir):
k_fold(os.path.join(data_dir, filename))
Alternatively, you could use glob to do both the listing (with full paths) and extension filtering:
import glob
for filename in glob.glob("/Users/my_name/PycharmProjects/My_Project/Data/Nod/Gyro/*.csv"):
k_fold(filename)

Python IOError: [Errno 2] No such file or directory:

I am just trying to open an image, I know there are several IOError questions on here, but I have not been able to understand the explanations.
The code i typed is here
from PIL import Image
image = Image.open("Lenna.png")
image.load()
The error obtained is as follows:
Traceback (most recent call last):
File "C:\Python27\hello world.py", line 4, in <module>
image = Image.open("Lenna.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: 'Lenna.png'
What do I do here?
Thank you.
You are trying to use relative filename. Python can't find such file in current work dir. Try to use full absolute path such as 'C:\Lenna.png'.
IOError: [Errno 2] No such file or directory: 'Lenna.png'
check path of the file
If you are trying to open image, either you have to specify the complete path of the image like,
from PIL import Image
im = Image.open('C:/Users/Anish/Desktop/2017PROJECTS/PYTHON_TWITTER/image/camel.png')
im.show()
Or you have to copy the image to the specified project directory and call the image name like,
im = Image.open('camel.png')

Open process and save specific images in related folder

I'm looking for a way to open and crop several tiff images and then save the new croped images created in the same folder (related to my script folder).
My current code looks like this:
from PIL import Image
import os,platform
filespath = os.path.join(os.environ['USERPROFILE'],"Desktop\Python\originalImagesfolder")
for file in os.listdir(filespath):
if file.endswith(".tif"):
im = Image.open(file)
im.crop((3000, 6600, 3700, 6750)).save(file+"_crop.tif")
This script is returning me the error:
Traceback (most recent call last):
File "C:\Users...\Desktop\Python\script.py", line 22, in
im = Image.open(file)
File "C:\Python34\lib\site-packages\PIL\Image.py", line 2219, in open
fp = builtins.open(fp, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'Image1Name.tif'
'Image1Name.tif' is the first tif image I'm trying to process in the folder. I don't get how the script can give the file's name without being able to find it. Any Help?
PS: I have 2 days experience in python and codes generaly speaking. Sorry if the answer is obvious
[EDIT/Update]
After modifying my initial code thanks to vttran and ChrisGuest answers, turning then into this:
from PIL import Image
import os,platform
filespath = os.path.join(os.environ['USERPROFILE'],"Desktop\Python\originalImagesfolder")
for file in os.listdir(filespath):
if file.endswith(".tif"):
filepath = os.path.join(filespath, file)
im = Image.open(filepath)
im.crop((3000, 6600, 3700, 6750)).save("crop"+file)
the script is returning me a new error message:
Traceback (most recent call last):
File "C:/Users/.../Desktop/Python/script.py", line 11, in
im.crop((3000, 6600, 3700, 6750)).save("crop"+file)
File "C:\Python34\lib\site-packages\PIL\Image.py", line 986, in crop
self.load()
File "C:\Python34\lib\site-packages\PIL\ImageFile.py", line 166, in load
self.load_prepare()
File "C:\Python34\lib\site-packages\PIL\ImageFile.py", line 250, in
load_prepare
self.im = Image.core.new(self.mode, self.size) ValueError: unrecognized mode
A maybe-useful information, it's a Landsat8 image in GeoTiff format. The TIFF file therefore include geoposition, projection... informations. The script works perfectly fine if I first open and re-save them with a software like Photoshop (16int tiff format).
When you are search for the file names you use filespath to specify the directory.
But then when you open the file, you are only using the base filename.
So you could replace
im = Image.open(file)
with
filepath = os.path.join(filespath, file)
im = Image.open(filepath)
Also consider using the glob module, as you can do glob.glob(r'path\*.tif) .
It is also good practice to avoid using builtin functions like file as variable names.

Categories

Resources