- 最近在使用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)