65 lines
2.0 KiB
Python
65 lines
2.0 KiB
Python
import os
|
||
from PIL import Image
|
||
from tqdm import tqdm
|
||
|
||
# --- 配置 ---
|
||
# 1. 设置您的图片文件夹路径
|
||
# 根据您的项目结构,这个路径应该是 'VOCdevkit/VOC2007/JPEGImages'
|
||
image_folder = '../label/up'
|
||
|
||
# 2. 是否删除转换后的原始 .jpeg 文件
|
||
delete_original = True
|
||
|
||
|
||
# --- 配置结束 ---
|
||
|
||
|
||
def convert_jpeg_to_jpg(folder_path, delete_original_file=True):
|
||
"""
|
||
将指定文件夹内的 .jpeg 图片转换为 .jpg 格式。
|
||
|
||
:param folder_path: 包含图片的文件夹路径。
|
||
:param delete_original_file: 是否删除原始的 .jpeg 文件。
|
||
"""
|
||
if not os.path.isdir(folder_path):
|
||
print(f"错误:文件夹 '{folder_path}' 不存在。")
|
||
return
|
||
|
||
# 找出所有.jpeg或.JPEG结尾的文件
|
||
jpeg_files = [f for f in os.listdir(folder_path) if f.lower().endswith('.jpeg')]
|
||
|
||
if not jpeg_files:
|
||
print(f"在 '{folder_path}' 中没有找到 .jpeg 文件。")
|
||
return
|
||
|
||
print(f"找到 {len(jpeg_files)} 个 .jpeg 文件,开始转换...")
|
||
|
||
for filename in tqdm(jpeg_files, desc="转换进度"):
|
||
jpeg_path = os.path.join(folder_path, filename)
|
||
|
||
# 构建新的 .jpg 文件名
|
||
base_name = os.path.splitext(filename)[0]
|
||
jpg_filename = f"{base_name}.jpg"
|
||
jpg_path = os.path.join(folder_path, jpg_filename)
|
||
|
||
try:
|
||
with Image.open(jpeg_path) as img:
|
||
# 确保图像是RGB模式,因为JPG不支持透明度
|
||
if img.mode != 'RGB':
|
||
img = img.convert('RGB')
|
||
|
||
# 以高质量保存为 .jpg
|
||
img.save(jpg_path, 'jpeg', quality=95)
|
||
|
||
# 如果转换成功且设置为删除,则删除原始文件
|
||
if delete_original_file:
|
||
os.remove(jpeg_path)
|
||
|
||
except Exception as e:
|
||
print(f"\n处理文件 '{filename}' 时出错: {e}")
|
||
|
||
print("\n转换完成!")
|
||
|
||
|
||
if __name__ == '__main__':
|
||
convert_jpeg_to_jpg(image_folder, delete_original) |