python中如何判断图片文件是否损坏及检查文件夹中的损坏图片文件

【时间】2018.11.25

【题目】python中如何判断图片文件是否损坏及检查文件夹中的损坏图片文件

概述

     在python中,可以使用imghdr模块中的what()方法判断图片文件是否损坏,若文件损坏,则返回None,否则返回图片文件的类型,如jpeg等。imghdr模块的具体内容见: https://docs.python.org/3/library/imghdr.html,最后给出了检查文件夹及其子文件夹中的损坏文件并将结果记录在txt文件中的代码。

一、imghdr.what()源码

def what(file, h=None):

    f = None

    try:

        if h is None:

            if isinstance(file, (str, PathLike)):

                f = open(file, 'rb')

                h = f.read(32)

            else:

                location = file.tell()

                h = file.read(32)

                file.seek(location)

        for tf in tests:

            res = tf(h, f)

            if res:

                return res

    finally:

        if f: f.close()

    return None

二、imghdr.what(file, h=None)的返回值

None  ---文件损坏

三、测试

使用图01.jpg和02.jpg(损坏)进行测试

测试代码:

import imghdr

img = imghdr.what('C:\\Users\\Administrator\\Desktop\\code\\preprocess\\test\\01.jpg')

print(img)

print(type(img))

img = imghdr.what('C:\\Users\\Administrator\\Desktop\\code\\preprocess\\test\\02.jpg')

print(img)

print(type(img))

运行结果:

四、检查文件夹及其子文件夹中的损坏文件并记录在txt文件中

【代码】

import os

import imghdr

from progressbar import ProgressBar

path ='C:\\Users\\Administrator\\Desktop\\code\\preprocess\\test'

original_images =[]

for root, dirs, filenames in os.walk(path):

    for filename in filenames:

        original_images.append(os.path.join(root, filename))

original_images = sorted(original_images)

print('num:',len(original_images))

f = open('check_error.txt','w+')

error_images =[]

progress = ProgressBar()

for filename in progress(original_images):

    check = imghdr.what(filename)

    if check == None:

        f.write(filename)

        f.write('\n')

        error_images.append(filename)

print(len(error_images))

f.seek(0)

for s in f:

    print(s)

f.close()

【运行结果】

txt文件:

 

 

 

 

  • 6
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值