gpt-4o-2024-08-06· openai
from WildChat-4.8M
使用python写出多线程处理读图获取图片尺寸的代码
Private research annotation
Sign in to add a private research label or note.
- User
使用python写出多线程处理读图获取图片尺寸的代码
- Assistant
使用Python多线程读取图像并获取其尺寸,你可以使用
threading模块和PIL(Pillow库,Python Imaging Library的一个分支)来处理图像。以下是一个示例代码:pythonimport os import threading from PIL import Image # 获取图片尺寸的函数 def get_image_size(image_path): try: with Image.open(image_path) as img: return img.size # img.size 是一个 tuple (width, height) except Exception as e: print(f"Error reading {image_path}: {e}") return None # 线程处理函数 def process_images(image_paths, results, index): for image_path in image_paths: size = get_image_size(image_path) if size: results[index].append((image_path, size)) # 主函数 def main(image_folder, num_threads=4): image_paths = [os.path.join(image_folder, f) for f in os.listdir(image_folder) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif'))] # 分割图片路径列表 split_paths = [image_paths[i::num_threads] for i in range(num_threads)] # 结果存储 results = [[] for _ in range(num_threads)] threads = [] # 创建并启动线程 for i in range(num_threads): thread = threading.Thread(target=process_images, args=(split_paths[i], results, i)) thread.start() threads.append(thread) # 等待所有线程完成 for thread in threads: thread.join() # 打印结果 for result in results: for image_path, size in result: print(f"Image: {image_path}, Size: {size}") if __name__ == "__main__": image_folder = "path_to_your_image_folder" main(image_folder)使用说明:
- 确保安装了Pillow库,可以使用命令
pip install pillow来安装。 - 替换
"path_to_your_image_folder"为你要处理的图像文件夹路径。
- 确保安装了Pillow库,可以使用命令