batch_resize.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import cv2
  2. import glob
  3. import os
  4. import time
  5. from pathlib import Path
  6. from concurrent.futures import ProcessPoolExecutor, as_completed
  7. from tqdm import tqdm
  8. def resize_image(img_path: str, target_size: tuple):
  9. try:
  10. # 读取图片
  11. img = cv2.imread(img_path)
  12. # 检查图片是否成功读取
  13. if img is None:
  14. print(f"警告: 无法读取图片 {img_path},已跳过。")
  15. return None
  16. # 缩放图片
  17. resized_img = cv2.resize(img, target_size)
  18. # 保存缩放后的图片
  19. cv2.imwrite(str(img_path), resized_img)
  20. return str(img_path)
  21. except Exception as e:
  22. # 捕获其他潜在错误
  23. print(f"处理图片 {img_path} 时发生错误: {e}")
  24. return None
  25. def main():
  26. INPUT_PATTERN = r'C:\Code\ML\Project\StitchImageServer\temp\Input\*\*.jpg'
  27. # 目标尺寸 (宽度, 高度)
  28. TARGET_SIZE = (1024, 1024)
  29. # 使用的进程数,None表示自动使用所有可用的CPU核心
  30. # 你也可以手动设置为一个整数,例如 4
  31. MAX_WORKERS = 4
  32. # 获取所有图片路径
  33. img_paths = glob.glob(INPUT_PATTERN)
  34. if not img_paths:
  35. print(f"在模式 '{INPUT_PATTERN}' 下未找到任何图片。")
  36. return
  37. print(f"找到 {len(img_paths)} 张图片待处理。")
  38. # --- 3. 使用进程池并行处理 ---
  39. start_time = time.time()
  40. processed_count = 0
  41. # 创建一个进程池
  42. with ProcessPoolExecutor(max_workers=MAX_WORKERS) as executor:
  43. futures = {executor.submit(resize_image, path, TARGET_SIZE): path for path in img_paths}
  44. # 使用 tqdm 创建进度条,并处理已完成的任务
  45. for future in tqdm(as_completed(futures), total=len(img_paths), desc="批量缩放图片"):
  46. result = future.result()
  47. if result:
  48. # 如果任务成功返回了输出路径,则计数加一
  49. processed_count += 1
  50. end_time = time.time()
  51. # --- 4. 打印总结 ---
  52. print("\n--- 任务完成 ---")
  53. print(f"成功处理了 {processed_count} / {len(img_paths)} 张图片。")
  54. print(f"总耗时: {end_time - start_time:.2f} 秒。")
  55. # 这个保护措施对于多进程编程至关重要
  56. if __name__ == '__main__':
  57. main()