脚本:数据裁剪 大图中裁出标注区域
目前这份代码还有问题,这个脚本存在一定的问题,好像是车辆位置和车牌位置的大小计算会出现错误,可以看看有道云笔记的实验记录
# -*- coding: utf-8 -*- """ Created on Sun Jan 12 2020 @author: ting.zou """ # import os # import cv2 import xml.etree.ElementTree as ET import pickle import os from os import listdir, getcwd from os.path import join import cv2 classes = ["car1","car2","car3","car4"] temp = ["car1_","car2_","car3_","car4_"] # 遍历指定目录,显示目录下的所有文件名 def CropImage4File(filepath,destpath): # list all the path or file in filepath pathDir = os.listdir(filepath) # test=0 for allDir in pathDir: # test = test+1 # if test >= 10: # break print('-------processing image ---------'+allDir) child = os.path.join(filepath, allDir) if os.path.isfile(child): image = cv2.imread(child) (image_id,ext) = os.path.splitext(allDir) in_file = open('LP_VOC/Annotations/%s.xml' % (image_id)) tree = ET.parse(in_file) root = tree.getroot() size = root.find('size') w = int(size.find('width').text) h = int(size.find('height').text) for obj in root.iter('object'): difficult = obj.find('difficult').text cls = obj.find('name').text if cls not in classes or int(difficult) == 1: continue cls_id = classes.index(cls) for subobj in root.iter('object'): subcls = subobj.find('name').text if temp[cls_id] in subcls: subname = subcls.split('_')[1] finalname = image_id+'_'+subname+'.jpg' #获取车牌坐标box subbox = subobj.find('bndbox') x3=int(subbox.find('xmin').text) x4=int(subbox.find('xmax').text) y3=int(subbox.find('ymin').text) y4=int(subbox.find('ymax').text) # print(finalname) dest = os.path.join(destpath,finalname) # 获取当前车辆box xmlbox = obj.find('bndbox') x1=int(xmlbox.find('xmin').text) x2=int(xmlbox.find('xmax').text) y1=int(xmlbox.find('ymin').text) y2=int(xmlbox.find('ymax').text) # 裁剪 # cropImg = image[y1:y2,x1:x2] #crop the image # cv2.imwrite(dest,cropImg)# write in destination path # 读取车牌在小车上的相对位置并写入新的txt文件 subx1=x3-x1 suby1=y3-y1 subx2=subx1+(x4-x3) suby2=suby1+(y4-y3) out_file = open('LP2/Annotations/%s.txt' % (finalname), 'w') out_file.write(str(subx1)+' '+str(suby1)+' '+str(subx2)+' '+str(suby2) + '\n') if __name__ == '__main__': filepath = 'LP_VOC/JPEGImages' destpath = 'LP2' CropImage4File(filepath,destpath)