起因:
在复现下面这个猫狗粉类代码时,总是遇到这样的报错:
(猫狗分类实战,推荐像我一样的纯小白阅读)https://blog.csdn.net/qq_33160678/article/details/108017822
博主说是因为路径问题,但是我仔细查看了路径应该是没问题的。而且最为迷惑的是,有时候一开始运行就报这个错,有时候则是运行了一会之后才出现这个错误。
经最强外挂(男朋友)提醒,代码能跑起来应该不是路径问题,应该是数据的问题。我打开data下的文件夹一看,嚯,真的有些图片是损坏的。
像这个910.jpg就无法打开,看来就是这种图片阻碍了我的程序。
男朋友提议,可以写一个脚本,剔除这些错误。其实我是不会写的(尴尬.jpg)
我在CSDN上找到了现成的代码,写的非常简洁优美,但是我试了试,不好用。
于是把里面的is_read_successfully(file)函数替换掉了,改用下面链接里的is_valid_image(path)函数。
https://www.jb51.net/article/171204.htm
测试,成功!感谢以上两位dalao的代码。
最后放上我的拼接成品哈哈哈哈哈哈哈
import os
import shutil
import warnings
import cv2
import io
from PIL import Image
warnings.filterwarnings("error", category=UserWarning)
base_dir = "/freespace/CAT_DOG/data/Cat/"
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)