深度学习过程中,数据的标注一般是由标注工程师完成,因为一些未知的失误或者数据传输存在的问题,导致图片损失或者xml标注文件存在错误,极易导致训练失败,让我们无法正确的完成训练,如下所示:
Corrupt JPEG data: 469 extraneous bytes before marker 0xd9
因此,在训练开始之前做数据清理(data cleaning)就显得十分必要。
数据处理–图片清理:
图片不完整的判定
def check_valid_image(sample_root, img_format=['.jpg', '.png', '.JPG', 'jpeg']):
for root, _, file_lst in os.walk(sample_root):
pbar = tqdm(file_lst, file=sys.stdout)
for file in pbar:
if os.path.splitext(file)[-1] in img_format:
category = root.split('\\')[-1]
img_path = os.path.join(root, file)
try:
# img.shape
img2 = Image.open(img_path).load()
except Exception as e:
print(img_path)
tqdm.write('[ERROR]:{}, {}'.format(category, file))
os.unlink(img_path)
pbar.set_description('Processing [{}]'.format(category))
print('Finish checking images.')
数据处理–xml处理
xml是否有误的操作
def check_xml_is_valid_full(sample_root, remove_or_not=False):
for root, _, file_lst in os.walk(sample_root):
pbar = tqdm(file_lst, file=sys.stdout)
for file in pbar:
if os.path.splitext(file)[-1] in ['.xml']:
category = root.split('\\')[-1]
xml_path = os.path.join(root, file)
try:
tree = ET.parse(xml_path)
root1 = tree.getroot()
size = root.findall('size')
# without gt labels
if len(size) == 0:
print(xml_path)
if remove_or_not:
os.remove(xml_path)
# size is not correct
obj = root1.findall('object')
if len(obj) == 0:
if remove_or_not:
os.remove(xml_path)
except:
tqdm.write('[ERROR]:{}, {}'.format(category, file))
pbar.set_description('Processing [{}]'.format(category))
print('Finish checking xmls.')
使用方式
if __name__ == '__main__':
sample_root = '你的图片xml地址'
check_valid_image(sample_root)
check_xml_is_valid_full(sample_root)
mark一下,用作记录!
图片出现有一半为灰色不完整情况
较好的方法就是判断jpg、jpeg、png文件结尾的标识。
JPG文件结尾标识:\xff\xd9
JPEG文件结尾标识:\xff\xd9
PNG文件结尾标识:\xaeB`\x82
代码后续验证了再发
参考:检测下载不完整、半截灰色的JPG、JPEG、PNG图片脚本
–END–