批量检测是否图片出现损坏或者为空的情况

import os
from PIL import Image

def check_and_delete_images(folder_path):
  for subdir in os.listdir(folder_path):
    subdir_path = os.path.join(folder_path, subdir)
    if os.path.isdir(subdir_path):
      for filename in os.listdir(subdir_path):
        if filename.endswith(".jpg") or filename.endswith(".jpeg"):
          file_path = os.path.join(subdir_path, filename)
          try:
            with Image.open(file_path) as img:
              # 检查图像是否为空
              if img.size[0] == 0 or img.size[1] == 0:
                print(f"{filename}: 图像为空,将被删除")
                # os.remove(file_path)
              else:
                # print(f"{filename}: 图像正常")
                continue
          except (IOError, SyntaxError) as e:
            print(f"{filename}: 图像损坏,将被删除,错误信息:{str(e)}")
            # os.remove(file_path)

# 替换为你的文件夹路径
folder_path = "/root/"+"autodl-tmp/yolov5/classify/caoyaodatas/train"
check_and_delete_images(folder_path)

你可能感兴趣的:(python脚本,python)