# 删除无效图片
import os
import shutil
import warnings
import cv2
import io
from PIL import Image
warnings.filterwarnings("error", category=UserWarning)
base_dir = "/home/deepl/LIJIA/fine-grain/DATA/mcm"
i = 0
'''
def is_read_successfully(file):
try:
imgFile = Image.open(file)
return True
except Exception:
return False
'''
def is_valid_image(path):
try:
bValid = True
fileObj = open(path, 'rb') # 以二进制形式打开
buf = fileObj.read()
if not buf.startswith(b'\xff\xd8'): # 是否以\xff\xd8开头
bValid = False
elif buf[6:10] in (b'JFIF', b'Exif'): # “JFIF”的ASCII码
if not buf.rstrip(b'\0\r\n').endswith(b'\xff\xd9'): # 是否以\xff\xd9结尾
bValid = False
else:
try:
Image.open(fileObj).verify()
except Exception as e:
bValid = False
print(e)
except Exception as e:
return False
return bValid
for parent, dirs, files in os.walk(base_dir):
for file in files:
#if not is_read_successfully(os.path.join(parent, file)):
if not is_valid_image(os.path.join(parent, file)):
print(os.path.join(parent, file))
os.remove(os.path.join(parent, file)) #真正使用时,这一行要放开,自己一般习惯先跑一遍,没有错误了再删除,防止删错。
i = i + 1
print(i)
遍历文件,删除无效图片
最新推荐文章于 2024-10-18 00:00:00 发布
这段代码定义了两个函数is_read_successfully和is_valid_image,用于检查图像文件是否成功读取和是否有效。在给定的base_dir目录下,遍历文件,如果文件不成功读取或验证失败,则打印文件路径并尝试删除。
摘要由CSDN通过智能技术生成