- 最近在使用labelme标注数据的过程中,因为有部分图片在下载的过程中出现问题,导致图片异常,而这些异常图片在使用labelme打开会触发异常,导致labelme自动关闭。
- 具体异常图片的样式就是一大片单一像素,导致图片显示不完整,这里不方便放图,就这么理解下吧。
- 手动删除这些异常图片真的很慢,效率低下,于是自己去根据labelme里面异常代码,单独提取出来用来删除这些异常图片。
具体代码如下
import io
import os
import os.path as osp
import logging
from PIL import Image, ExifTags, ImageOps
def load_image_file(filename):
try:
image_pil = Image.open(filename)
except IOError:
logging.error('Failed opening image file: {}'.format(filename))
raise IOError('Failed opening image file: {}'.format(filename))
with io.BytesIO() as f:
ext = osp.splitext(filename)[1].lower()
if ext in ['.jpg', '.jpeg']:
format = 'JPEG'
else:
format = 'PNG'
image_pil.save(f, format=format)
f.seek(0)
result = f.read()
return result
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO, format="%(levelname)s:%(message)s")
dir_path = r"C:\Users\wd526\Desktop\***"
images = os.listdir(dir_path)
err_image = []
for image in images:
try:
load_image_file(os.path.join(dir_path, image))
logging.info(f"successful: {image}")
except OSError as e:
command = f"rm {dir_path}\\{image}"
err_image.append(command)
logging.error(f"Error: {e}, Index: {images.index(image)}, err_image: {len(err_image)}")
for command in err_image:
logging.error(f'Command: {command}')
os.system(command)