使用concurrent.futures.threadThreadPoolExecutor()实现多线程图片处理
发布时间:2023-12-15 05:57:50
使用concurrent.futures.threadThreadPoolExecutor()实现多线程图片处理的步骤如下:
1. 首先导入必要的库文件:
from concurrent.futures import ThreadPoolExecutor from PIL import Image import os
2. 创建一个函数来处理图片,例如将图片缩放为指定尺寸并保存:
def process_image(file_path, output_path, size):
# 打开图片
img = Image.open(file_path)
# 缩放图片
img.thumbnail(size)
# 保存图片
file_name = os.path.basename(file_path)
img.save(os.path.join(output_path, f"processed_{file_name}"))
print(f"Processed image: {file_name}")
3. 创建一个函数来遍历指定目录下的所有图片,并调用线程池来处理图片:
def process_images(input_path, output_path, size, num_threads):
# 获取目录下的所有文件
files = [os.path.join(input_path, file) for file in os.listdir(input_path) if file.endswith('.jpg') or file.endswith('.png')]
# 创建线程池
with ThreadPoolExecutor(max_workers=num_threads) as executor:
# 提交每个图片处理任务给线程池
for file in files:
executor.submit(process_image, file, output_path, size)
4. 在主程序中调用process_images函数来进行图片处理:
if __name__ == "__main__":
input_path = "/path/to/input/folder"
output_path = "/path/to/output/folder"
size = (800, 600) # 指定缩放尺寸
num_threads = 4 # 指定线程数量
process_images(input_path, output_path, size, num_threads)
在上述例子中,我们使用concurrent.futures.threadThreadPoolExecutor()来创建一个线程池,并使用ThreadPoolExecutor.submit()方法来提交每个图片处理任务给线程池。线程池会自动分配线程来执行任务,从而实现多线程图片处理。
需要注意的是,有一些操作需要加锁以避免线程冲突,例如创建目录或者保存图片时,可以使用threading.Lock来进行线程间的同步操作。
