0

I am working on changes my TIF files to JPEGs in order to run a object detection tool on them. I found a solution here (answer given by user2019716), but for some reason my files are not being read. The only line a changed was the first one. I wanted to use a different directory. Did I screw up the path some how?

import os, sys
from PIL import Image

for infile in os.listdir("C:/Users/NAME/Desktop/FOLDER"):
    print("file : " + infile)
    if infile[-3:] == "tif" or infile[-3:] == "bmp" :
       outfile = infile[:-3] + "jpeg"
       im = Image.open(infile)
       print("new filename : " + outfile)
       out = im.convert("RGB")
       out.save(outfile, "JPEG", quality=90)

Error:

C:\Users\NAME\anaconda3\envs\Scripts\python.exe C:\Users\NAME\Desktop\Scripts\TIFF_to_JPG.py
file : __0.tif
Traceback (most recent call last):
  File "C:\Users\NAME\Desktop\Scripts\TIFF_to_JPG.py", line 10, in <module>
    im = Image.open(infile)
  File "C:\Users\NAME\anaconda3\envs\Scripts\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'

Process finished with exit code 1
Binx
  • 382
  • 7
  • 22

1 Answers1

1

Do you run the code from "C:/Users/NAME/Desktop/FOLDER" ? If not, that causes the error because you only provide the name of the file, not the absolute path. Python expects to find the file in the directory you run the code from. You can try:

# -*- coding: utf-8 -*-

import os
from PIL import Image

input_dir = "C:/Users/NAME/Desktop/FOLDER/"
# This can differ from input_dir
output_dir = "C:/Users/NAME/Desktop/FOLDER/"

for infile in os.listdir(input_dir):
    print("file : " + infile)
    if infile[-3:] == "tif" or infile[-3:] == "bmp" :
       outfile = infile[:-3] + "jpeg"
       im = Image.open(input_dir + infile)
       print("new filename : " + outfile)
       out = im.convert("RGB")
       save_path = output_dir + outfile 
       out.save(save_path, "JPEG", quality=90)
Antoine Collet
  • 348
  • 2
  • 14
  • I am running the code from "C:/Users/NAME/Desktop/FOLDER". What you have works, but I do not understand why. I did input the absolute path for the "input_dir". – Binx Nov 11 '20 at 22:47
  • Well, that is strange indeed. To be sure, add ```print(os.getcwd()) ```. It gives you the path you are running the code from. – Antoine Collet Nov 12 '20 at 13:35