From a989385b417a1244fc7ee9637e829b7ecd815940 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BE=99=E6=BE=B3?= Date: Tue, 14 Jan 2025 21:23:19 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9tools/jpg=E6=A0=BC=E5=BC=8F?= =?UTF-8?q?=E8=BD=AC=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/convert_jpg.py | 45 +++++++++++++++++++++++++++++++++++--------- 1 file changed, 36 insertions(+), 9 deletions(-) diff --git a/tools/convert_jpg.py b/tools/convert_jpg.py index 402a8cb..fd9bf97 100644 --- a/tools/convert_jpg.py +++ b/tools/convert_jpg.py @@ -1,14 +1,41 @@ from PIL import Image import os +import shutil +from multiprocessing import Pool +from functools import partial -convert_format = "tif" -img_dir = r"E:\datasets\UAV\134\project\images" -output_dir = r"E:\datasets\UAV\134_tif\project\images" +def convert_image(file_name, img_dir, output_dir, convert_format): + input_path = os.path.join(img_dir, file_name) + output_path = os.path.join(output_dir, file_name.replace(".jpg", f".{convert_format}")) + + # 打开并转换图像 + img = Image.open(input_path) + img.save(output_path) -for file_name in os.listdir(img_dir): - img = Image.open(os.path.join(img_dir, file_name)) - if convert_format == "png": - img.save(os.path.join(output_dir, file_name.replace(".jpg", ".png"))) - elif convert_format == "tif": - img.save(os.path.join(output_dir, file_name.replace(".jpg", ".tif")), "TIFF") +def main(): + convert_format = "tif" + img_dir = r"E:\datasets\UAV\134\project\images" + output_dir = r"E:\datasets\UAV\134_tif\project\images" + # 如果输出目录存在,先删除 + if os.path.exists(output_dir): + shutil.rmtree(output_dir) + + # 创建输出目录 + os.makedirs(output_dir) + + # 获取所有文件名 + file_names = os.listdir(img_dir) + + # 创建部分函数,固定除文件名外的其他参数 + convert_partial = partial(convert_image, + img_dir=img_dir, + output_dir=output_dir, + convert_format=convert_format) + + # 使用进程池并行处理 + with Pool() as pool: + pool.map(convert_partial, file_names) + +if __name__ == '__main__': + main()