我们做机器学习的时候,总会用到很多训练集,然后我们的数据比较少的时候,就可以将图片翻转标注。代码如下:
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/6/28 13:59 # @Author : xiaodai import cv2 from PIL import Image import xml.etree.ElementTree as ET from tqdm import tqdm import os def flip_horizontal(jpg_file,new_jpg): im = Image.open(jpg_file) # out = im.transpose(Image.ROTATE_180) out = im.transpose(Image.FLIP_LEFT_RIGHT) out.save(new_jpg) def flip_xml(xml_file,new_xml): tree = ET.parse(xml_file) objs = tree.findall('object') for ix, obj in enumerate(objs): name = obj.find('name').text if name == 'mouse': print(xml_file) obj_new = obj.find('bndbox') xmin = str( 1280 - int(obj_new.find('xmin').text)) xmax = str( 1280 - int(obj_new.find('xmax').text)) obj_new.find('xmin').text = xmin obj_new.find('xmax').text = xmax tree.write(new_xml) if __name__ == '__main__': path = r'F: emp12355_38 625mouse' xml_files = [os.path.join(rootdir, file) for rootdir, _, files in os.walk(path) for file in files if (file.endswith('.xml'))] jpg_files =[xmlfile.replace('Annotations','JPEGImages').replace('xml','jpg') for xmlfile in xml_files] files = zip(jpg_files,xml_files) for jpg_file,xml_file in tqdm(files): new_jpg = jpg_file.replace(jpg_file.split('\')[-1].split('.')[0],jpg_file.split('\')[-1].split('.')[0] + '_filp') new_xml = new_jpg.replace('JPEGImages', 'Annotations').replace('jpg', 'xml') flip_xml(xml_file,new_xml) flip_horizontal(jpg_file, new_jpg)