trans_images.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. import os
  4. from PIL import Image
  5. folder_path = "/Users/zhenqin/Downloads/钢绳" # Replace with the actual folder path
  6. # 1.将图片统一为纵向 --------------------------------------------------------------------------------------------------
  7. # Iterate over the files in the folder
  8. for filename in os.listdir(folder_path):
  9. if filename.endswith(".jpg") or filename.endswith(".png"): # Adjust file extensions as needed
  10. file_path = os.path.join(folder_path, filename)
  11. # Open the image
  12. image = Image.open(file_path)
  13. width, height = image.size
  14. # Compare horizontal and vertical pixel values
  15. if width > height:
  16. # Rotate the image 90 degrees clockwise
  17. rotated_image = image.rotate(-90, expand=True)
  18. # Save the rotated image, overwrite the original file
  19. rotated_image.save(file_path)
  20. print(f"Image '{filename}' rotated.")
  21. else:
  22. print(f"No operation required for image '{filename}'.")
  23. # 2.统一图片分辨率 --------------------------------------------------------------------------------------------------
  24. def resize_images(folder_path, target_resolution):
  25. # 遍历文件夹中的所有文件
  26. for filename in os.listdir(folder_path):
  27. file_path = os.path.join(folder_path, filename)
  28. # 检查文件是否是图片
  29. if not os.path.isfile(file_path) or not any(
  30. file_path.endswith(extension) for extension in ['.jpg', '.jpeg', '.png']):
  31. continue
  32. # 打开图片
  33. image = Image.open(file_path)
  34. # 获取原始分辨率
  35. original_resolution = image.size
  36. # 计算调整比例
  37. ratio = min(target_resolution[0] / original_resolution[0], target_resolution[1] / original_resolution[1])
  38. # 计算调整后的尺寸
  39. resized_size = (int(original_resolution[0] * ratio), int(original_resolution[1] * ratio))
  40. # 调整图片分辨率
  41. resized_image = image.resize(resized_size)
  42. # 创建空白画布
  43. canvas = Image.new('RGB', target_resolution, (255, 255, 255))
  44. # 在画布上居中粘贴调整后的图片
  45. offset = ((target_resolution[0] - resized_size[0]) // 2, (target_resolution[1] - resized_size[1]) // 2)
  46. canvas.paste(resized_image, offset)
  47. # 保存调整后的图片
  48. canvas.save(file_path)
  49. # 指定文件夹路径和目标分辨率
  50. target_resolution = (460, 460) # 替换为你的目标分辨率
  51. # 调用函数进行图片分辨率统一
  52. resize_images(folder_path, target_resolution)