Binx
Binx

Reputation: 414

Python: Convert TIF to JPEG

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

Upvotes: 0

Views: 838

Answers (1)

Antoine Collet
Antoine Collet

Reputation: 358

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)

Upvotes: 1

Related Questions