我正在将TIF文件更改为JPEG,以便对其运行对象检测工具。我找到了解决方法here(由user2019716给出的答案),但是由于某种原因,我的文件无法读取。更改的唯一一行是第一行。我想使用其他目录。我是否以某种方式搞砸了路径?
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)
错误:
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
答案 0 :(得分:1)
您是否从“ C:/用户/名称/桌面/文件夹”运行代码?否则,将导致错误,因为您仅提供文件名,而不是绝对路径。如果您从中运行代码,则Python希望找到该文件。您可以尝试:
# -*- 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)