Search code examples
pythonpycharmpython-imaging-libraryjpegtiff

TIF to JPEG Conversion - No such file or directory


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

enter image description here enter image description here


Solution

  • 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