遍历文件,删除无效图片

这段代码定义了两个函数is_read_successfully和is_valid_image,用于检查图像文件是否成功读取和是否有效。在给定的base_dir目录下,遍历文件,如果文件不成功读取或验证失败,则打印文件路径并尝试删除。
摘要由CSDN通过智能技术生成
# 删除无效图片
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)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值