有的数据集中存在着各不相同的图片格式,在训练数据集时可能会出现一些警告。警告文件格式问题:libpng warning: iCCP: known incorrect sRGB profile。数据集中存在不同的图片格式,JEPG、png文件格式,把他们都转换为jpg格式后,警告就能消除。
import os
from PIL import Image
def convert_images_to_jpg(input_folder, output_folder):
# 创建输出文件夹(如果不存在)
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# 遍历输入文件夹中的所有文件
for filename in os.listdir(input_folder):
if filename.lower().endswith(('.png', '.jpeg', '.bmp', '.gif', '.tiff')):
# 构建文件的完整路径
file_path = os.path.join(input_folder, filename)
try:
# 打开图像
with Image.open(file_path) as img:
# 转换为 JPG 格式
jpg_filename = f"{os.path.splitext(filename)[0]}.jpg"
output_path = os.path.join(output_folder, jpg_filename)
img.convert('RGB').save(output_path, 'JPEG')
print(f"Converted: {filename} to {jpg_filename}")
except Exception as e:
print(f"Could not convert {filename}: {e}")
elif filename.lower().endswith('.jpg'):
# 复制原 JPG 文件到输出文件夹
original_jpg_path = os.path.join(input_folder, filename)
output_jpg_path = os.path.join(output_folder, filename)
try:
with open(original_jpg_path, 'rb') as f:
with open(output_jpg_path, 'wb') as out_f:
out_f.write(f.read())
print(f"Copied: {filename} to {output_jpg_path}")
except Exception as e:
print(f"Could not copy {filename}: {e}")
# 使用示例
input_folder = 'path/to/your/input_folder' # 替换为你的输入文件夹路径
output_folder = 'path/to/your/output_folder' # 替换为你的输出文件夹路径
convert_images_to_jpg(input_folder, output_folder)