def write_xml(self): imgFolderName = ustr(self.image_path).split('/')[-2] print imgFolderName #imgFileName = str(self.image_path).split('/')[-1] imgFileNameWithoutExt = ustr(self.image_path).split('.')[0] print imgFileNameWithoutExt image = QtGui.QImage() image.load(ustr(self.image_path)) imageShape = [ image.height(), image.width(), 1 if image.isGrayscale() else 3 ] writer = PascalVocWriter(imgFolderName, imgFileNameWithoutExt, imageShape, localImgPath=ustr(self.image_path)) #writer.verified = self.verified item = {} item['name'] = '' item['flood1name'] = imgFileNameWithoutExt + '_index.bmp' item['flood2name'] = imgFileNameWithoutExt + '_category.bmp' writer.addObject(item['name'], item['flood1name'], item['flood2name']) writer.save() return
def label_filter(self, labels, new_dir): flist = [] for lb in labels: stemp = self.find_label(lb) for fname in stemp: if (fname in flist) == False: flist.append(fname) for filename in flist: filepath = self.anno_path + '/' + filename + '.xml' pr = PR(filepath) shapes = pr.getShapes() sl = pr.getSources() localpath = os.path.join(self.im_path, sl['filename']) pw = PW(sl['folder'], sl['filename'], sl['size'], databaseSrc='Unknown', localImgPath=localpath) pw.verified = True for shape in shapes: if shape[0] in labels: label = shape[0] difficult = 0 bndbox = shape[1] pw.addBndBox(bndbox[0][0], bndbox[0][1], bndbox[2][0], bndbox[2][1], label, difficult) pw.save(new_dir + '/' + filename + '.xml')
def savePascalVocFormat(self, filename, shapes, imagePath, imageData, lineColor=None, fillColor=None, databaseSrc=None): imgFolderPath = os.path.dirname(imagePath) imgFolderName = os.path.split(imgFolderPath)[-1] imgFileName = os.path.basename(imagePath) imgFileNameWithoutExt = os.path.splitext(imgFileName)[0] # Read from file path because self.imageData might be empty if saving to # Pascal format image = QImage() image.load(imagePath) imageShape = [ image.height(), image.width(), 1 if image.isGrayscale() else 3 ] writer = PascalVocWriter(imgFolderName, imgFileNameWithoutExt, imageShape, localImgPath=imagePath) for shape in shapes: points = shape['points'] label = shape['label'] bndbox = LabelFile.convertPoints2BndBox(points) writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], bndbox[3], label) writer.save(targetFile=filename) return
def del_label(self, label_del): flist = os.listdir(self.anno_path) for filename in flist: filepath = self.anno_path + '/' + filename pr = PR(filepath) shapes = pr.getShapes() sl = pr.getSources() localpath = os.path.join(self.im_path, sl['filename']) pw = PW(sl['folder'], sl['filename'], sl['size'], databaseSrc='Unknown', localImgPath=localpath) pw.verified = True for shape in shapes: if shape[0] != label_del: label = shape[0] difficult = 0 bndbox = shape[1] pw.addBndBox(bndbox[0][0], bndbox[0][1], bndbox[2][0], bndbox[2][1], label, difficult) pw.save(filepath)
def save_pascal_voc_format(xml_file_path, shapes, imagePath, imageData, lineColor=None, fillColor=None, databaseSrc=None): imgFolderPath = os.path.dirname(imagePath) imgFolderName = os.path.split(imgFolderPath)[-1] imgFileName = os.path.basename(imagePath) #imgFileNameWithoutExt = os.path.splitext(imgFileName)[0] # Read from file path because self.imageData might be empty if saving to # Pascal format imageH, imageW = imageData.shape[:2] imageShape = [imageH, imageW] writer = PascalVocWriter(imgFolderName, imgFileName, imageShape, localImgPath=imagePath) for shape in shapes: difficult = 0 bndbox, label = shape xmin = bndbox[1] * imageW ymin = bndbox[0] * imageH xmax = bndbox[3] * imageW ymax = bndbox[2] * imageH writer.addBndBox(xmin, ymin, xmax, ymax, label, difficult) writer.save(targetFile=xml_file_path)
def test_upper(self): dir_name = os.path.abspath(os.path.dirname(__file__)) libs_path = os.path.join(dir_name, '..', 'libs') sys.path.insert(0, libs_path) from pascal_voc_io import PascalVocWriter from pascal_voc_io import PascalVocReader # Test Write/Read writer = PascalVocWriter('tests', 'test', (512, 512, 1), localImgPath='tests/test.bmp') writer.addBndBox(60, 40, 430, 504, 'person', dict(difficult=1)) writer.addBndBox(113, 40, 450, 403, 'face', dict(difficult=1)) writer.save('tests/test.xml') reader = PascalVocReader('tests/test.xml') shapes = reader.getShapes() personBndBox = shapes[0] face = shapes[1] self.assertEqual(personBndBox[0], 'person') self.assertEqual(personBndBox[1], [(60, 40), (430, 40), (430, 504), (60, 504)]) self.assertEqual(face[0], 'face') self.assertEqual(face[1], [(113, 40), (450, 40), (450, 403), (113, 403)])
def savePascalVocFormat(self, filename, shapes, imagePath, imageData, lineColor=None, fillColor=None, databaseSrc=None): imgFolderPath = os.path.dirname(imagePath) imgFolderName = os.path.split(imgFolderPath)[-1] imgFileName = os.path.basename(imagePath) imgFileNameWithoutExt = os.path.splitext(imgFileName)[0] # imageData contains x,y,z, depth extensions imageShape = [imageData[0], imageData[1], imageData[2], imageData[3]] writer = PascalVocWriter(imgFolderName, imgFileNameWithoutExt+".tif",\ imageShape, localImgPath=imagePath) bSave = False for shape in shapes: points = shape['points'] label = shape['label'] bndbox = LabelFile.convertPoints2BndBox(points) writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], bndbox[3], bndbox[4], bndbox[5], label) bSave = True if bSave: writer.save(targetFile=filename) return
def process_voc_file(file_name, category_id, category, type, num, OUTPUT_LOCATION): count = 0 with open(file_name) as meta_file: meta_obj_list = json.load(meta_file) for meta_obj in meta_obj_list: if count >= num: break else: print count # type = "val" if type == "test" else type try: photo_id = meta_obj["photo"] bbox = meta_obj["bbox"] width = bbox["width"] top = bbox["top"] left = bbox["left"] height = bbox["height"] image_file = OUTPUT_LOCATION + "/JPEGImages/" + str(photo_id) image = Image.open(BASE_IMAGE_LOCATION + "/" + str(photo_id) + ".jpg") create_folder_if_not_exist(image_file + ".jpg") p = Popen([ 'cp', BASE_IMAGE_LOCATION + "/" + str(photo_id) + ".jpg", image_file + ".jpg" ]) p.wait() tmp = PascalVocWriter('train', str(photo_id) + ".jpg", (image.size[0], image.size[1], 3), "street2photo", file_name) tmp.addBndBox(left, top, left + width, top + height, category) annotation_file = OUTPUT_LOCATION + "/" + "Annotations/" + str( photo_id) + ".xml" create_folder_if_not_exist(annotation_file) tmp.save(annotation_file) create_folder_if_not_exist(OUTPUT_LOCATION + "/" + "ImageSets/Main/" + type + ".txt") lock.acquire() f = open( OUTPUT_LOCATION + "/" + "ImageSets/Main/" + type + ".txt", "a+") f.write(image_file + "\n") f.close() lock.release() count += 1 except Exception, e: import traceback traceback.print_exc(e)
def process(image,background,objectName,xml,jpeg): """ :param image: input image filename :param background: background filename :param objectName: name of object :param xml: xml filename :param jpeg: jpeg image filename :return: write annotation to xml """ if type(image) == str: cvin=cv2.imread(image) if cvin is None: print('cannot open image %s' % image) sys.exit(-1) elif type(image) == numpy.ndarray: cvin=image else: print('invalided image') sys.exit(-1) if type(background) == str: cvbg=cv2.imread(background) if cvbg is None : print('cannot open background %s'%background) sys.exit(-1) elif type(background) == numpy.ndarray: cvbg=background else: print('invalided background') sys.exit(-1) assert(len(cvin.shape)==3) assert(len(cvbg.shape)==3) cvin=classify2detect.resize(cvin,cvbg) shapein=cvin.shape shapebg=cvbg.shape shift=[0,0] shift[0]=shapebg[0]-shapein[0] shift[1]=shapebg[1]-shapein[1] top=random.randint(1,shift[0]-1) left=random.randint(1,shift[1]-1) right=left+shapein[1] bottom=top+shapein[0] cvjpeg=classify2detect.merge(cvin,cvbg,[top,left]) cv2.imwrite(jpeg,cvjpeg) xmlwriter=PascalVocWriter(foldername='./', filename=jpeg, imgSize=shapebg) xmlwriter.addBndBox(xmin=left, ymin=top, xmax=right, ymax=bottom, name=objectName, difficult=0) xmlwriter.save(targetFile=xml)
def write_xml(image_file_name, img_folder_name, img_size, bndbox, label): imagePath = os.path.join(img_folder_name, image_file_name) writer = PascalVocWriter(img_folder_name, image_file_name, (img_size[0], img_size[1], 3), localImgPath=imagePath, usrname="auto") writer.verified = True writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], bndbox[3], label, 0) writer.save(targetFile=imagePath[:-4] + XML_EXT)
def savePascalVocFormat(self, filename, shapes, imagePath, imageData, lineColor=None, fillColor=None, databaseSrc=None): imgFolderPath = os.path.dirname(imagePath) imgFolderName = os.path.split(imgFolderPath)[-1] imgFileName = os.path.basename(imagePath) imgFileNameWithoutExt = os.path.splitext(imgFileName)[0] # Read from file path because self.imageData might be empty if saving to # Pascal format image = QImage() image.load(imagePath) imageShape = [ image.height(), image.width(), 1 if image.isGrayscale() else 3 ] writer = PascalVocWriter(imgFolderName, imgFileNameWithoutExt, imageShape, localImgPath=imagePath) writer.verified = self.verified for shape in shapes: points = shape['points'] label = shape['label'] # Add Chris difficult = int(shape['difficult']) direction = shape['direction'] isRotated = shape['isRotated'] # if shape is normal box, save as bounding box # print('direction is %lf' % direction) if not isRotated: bndbox = LabelFile.convertPoints2BndBox(points) writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], bndbox[3], label, difficult) else: #if shape is rotated box, save as rotated bounding box robndbox = LabelFile.convertPoints2RotatedBndBox(shape) ''' writer.addRotatedBndBox(robndbox[0],robndbox[1], robndbox[2],robndbox[3],robndbox[4],label,difficult) ''' # CC Wang 2019/10/17 writer.addRotatedBndBox(robndbox[0], robndbox[1], robndbox[2], robndbox[3], robndbox[4], robndbox[5], robndbox[6], robndbox[7], robndbox[8], robndbox[9], robndbox[10], robndbox[11], robndbox[12], label, difficult) writer.save(targetFile=filename) return
def gen_voc_label(self, folder_name, file_name, img_size, img_path): writer = PascalVocWriter(folder_name, file_name + '.jpg', img_size, localImgPath=img_path) difficult = 0 for i, roi in enumerate(self.rois): writer.addBndBox(roi[0], roi[1], roi[2], roi[3], self.rect_classes[i], difficult) writer.save(folder_name + '/' + file_name + '.xml') print('labelxml saved:', folder_name + '/' + file_name + '.xml')
def write_xmls(foldername, gt_dict, num_raw_imgs, save_dir): imgs = list(gt_dict.keys()) annotations = list(gt_dict.values()) imgSize = [HEIGHT, WIDTH, 3] for i in range(num_raw_imgs, len(imgs)): filename = imgs[i] # print(i, filename) localImgPath = os.path.join(foldername, filename) XMLWriter = PascalVocWriter(foldername, filename, imgSize, localImgPath) for box in annotations[i]: XMLWriter.addBndBox(box[1], box[2], box[1] + box[3], box[2] + box[4], str(box[0])) XMLWriter.save(os.path.join(save_dir, filename[:-4] + '.xml'))
def savePascalVocFormat(self, filename, shapes, imagePath, imageData, lineColor=None, fillColor=None, databaseSrc=None): imgFolderPath = os.path.dirname(imagePath) #加载文件所在路径 imgFolderName = os.path.split(imgFolderPath)[-1] #获取文件所在文件夹名称 imgFileName = os.path.basename(imagePath) #获取文件名(包含文件扩展名,即形如1.jpg) imgFileNameWithoutExt = os.path.splitext(imgFileName)[ 0] #os.path.splitext将文件名和扩展名分开,这里只取文件名 # Read from file path because self.imageData might be empty if saving to # Pascal format image = QImage() image.load(imagePath) #加载图像 imageShape = [ image.height(), image.width(), 1 if image.isGrayscale() else 3 ] #获取图像的width,height和depth writer = PascalVocWriter(imgFolderName, imgFileNameWithoutExt, imageShape, localImgPath=imagePath) writer.verified = self.verified for shape in shapes: points = shape['points'] label = shape['label'] # Add Chris difficult = int(shape['difficult']) direction = shape['direction'] isRotated = shape['isRotated'] # if shape is normal box, save as bounding box # print('direction is %lf' % direction) if not isRotated: bndbox = LabelFile.convertPoints2BndBox(points) writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], bndbox[3], label, difficult) else: #if shape is rotated box, save as rotated bounding box robndbox = LabelFile.convertPoints2RotatedBndBox(shape) writer.addRotatedBndBox(robndbox[0], robndbox[1], robndbox[2], robndbox[3], robndbox[4], label, difficult) writer.save(targetFile=filename) #保存 return
def parse_json_to_xml(json_file, classes): #read json data with open(json_file, 'r') as f: data = json.loads(f.read()) folder_name = os.path.dirname(json_file) file_name = data['filename'] image_size = data['image_size'] boxes = data['box'] #init parser parser = PascalVocWriter(folder_name, file_name, image_size) for b in boxes: parser.add_bnd_box(b[0], b[1], b[2], b[3], classes, 0) parser.save()
def savePascalVocFormat(self, filename, shapes, imagePath, imageData, lineColor=None, fillColor=None, databaseSrc=None): imgFolderPath = os.path.dirname(imagePath) imgFolderName = os.path.split(imgFolderPath)[-1] imgFileName = os.path.basename(imagePath) imgFileNameWithoutExt = os.path.splitext(imgFileName)[0] # Read from file path because self.imageData might be empty if saving to # Pascal format image = QImage() image.load(imagePath) imageShape = [ image.height(), image.width(), 1 if image.isGrayscale() else 3 ] writer = PascalVocWriter(imgFolderName, imgFileNameWithoutExt, imageShape, localImgPath=imagePath) writer.verified = self.verified w, h = image.width(), image.height() for shape in shapes: print(shape['type']) points = shape['points'] self.constrainPoints(points, w, h) label = shape['label'] if shape['type'] == 'Rect': bndbox = LabelFile.convertPoints2BndBox(points) writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], bndbox[3], label, 'Rect') elif shape['type'] == 'Point': point = points[0] writer.addPoint(point[0], point[1], label, 'Point') elif shape['type'] == 'Polygon': polygon = LabelFile.convertPoints2Polygon(points) writer.addPolygon(polygon[0], polygon[1], polygon[2], polygon[3], polygon[4], polygon[5], polygon[6], polygon[7], label, 'Polygon') writer.save(targetFile=filename) return
def convert(image_path, annotation_path): save_path = os.path.join(os.path.dirname(annotation_path), "xml_converted") if not os.path.exists(save_path): os.makedirs(save_path) for file in os.listdir(annotation_path): if file.endswith(".txt") and file != "classes.txt": #print("Convert", file) annotation_no_txt = os.path.splitext(file)[0] imagePath = image_path + "/" + annotation_no_txt + ".jpg" image = QImage() image.load(imagePath) imageShape = [ image.height(), image.width(), 1 if image.isGrayscale() else 3 ] imgFolderName = os.path.basename(annotation_path) imgFileName = os.path.basename(imagePath) writer = PascalVocWriter(imgFolderName, imgFileName, imageShape, localImgPath=imagePath) # Read YOLO file txtPath = annotation_path + "/" + file tYoloParseReader = YoloReader(txtPath, image) shapes = tYoloParseReader.getShapes() num_of_box = len(shapes) for i in range(num_of_box): label = shapes[i][0] xmin = shapes[i][1][0][0] ymin = shapes[i][1][0][1] x_max = shapes[i][1][2][0] y_max = shapes[i][1][2][1] writer.addBndBox(xmin, ymin, x_max, y_max, label, 0) writer.save(targetFile=save_path + "/" + annotation_no_txt + ".xml")
def savePascalVocFormat(self, username, filename, shapes, imagePath, imageData, lineColor=None, fillColor=None, databaseSrc=None): imgFolderPath = os.path.dirname(imagePath) imgFolderName = os.path.split(imgFolderPath)[-1] imgFileName = os.path.basename(imagePath) imgFileNameWithoutExt = os.path.splitext(imgFileName)[0] # Read from file path because self.imageData might be empty if saving to # Pascal format image = QImage() image.load(imagePath) imageShape = [ image.height(), image.width(), 1 if image.isGrayscale() else 3 ] writer = PascalVocWriter(username, imgFolderName, imgFileNameWithoutExt, imageShape, localImgPath=imagePath) # print imgFileNameWithoutExt writer.verified = self.verified for shape in shapes: points = shape['points'] #>>>delete(1) label = shape['label'] bndbox = LabelFile.convertPoints2BndBox(points) writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], bndbox[3]) #>>>delete(1), label # print '???',filename if filename.split('.')[1] == 'jpg': filename = filename.split('.')[0] + '.xml' # print '!!!???',filename writer.save(targetFile=filename) return
def convert_coco2_voc(json_file, save_dir): coco = COCO(json_file) classes_dict = catid2name(coco) for cat in classes: catIds = coco.getCatIds(catNms=[cat]) if len(catIds) == 0: continue imgIds = coco.getImgIds(catIds=catIds) for imgId in tqdm(imgIds): img = coco.loadImgs(imgId)[0] filename = img['file_name'] height = img['height'] width = img['width'] annIds = coco.getAnnIds(imgIds=img['id'], catIds=catIds, iscrowd=None) anns = coco.loadAnns(annIds) if len(anns) == 0: continue writer = PascalVocWriter(filename, filename, (height, width, 3), localImgPath=filename) writer.verified = True objs = [] for ann in anns: name = classes_dict[ann['category_id']] if name in classes: if 'bbox' in ann: bbox = ann['bbox'] xmin = (int)(bbox[0]) ymin = (int)(bbox[1]) xmax = (int)(bbox[2] + bbox[0]) ymax = (int)(bbox[3] + bbox[1]) obj = [name, 1.0, xmin, ymin, xmax, ymax] objs.append(obj) writer.addBndBox(xmin, ymin, xmax, ymax, name, 0) writer.save(os.path.join(save_dir, filename.replace("jpg", "xml")))
def savePascalVocFormat( self, savefilename, image_size, shapes, imagePath=None, databaseSrc=None, shape_type_='RECT'): imgFolderPath = os.path.dirname(imagePath) imgFolderName = os.path.split(imgFolderPath)[-1] imgFileName = os.path.basename(imagePath) imgFileNameWithoutExt = os.path.splitext(imgFileName)[0] #img = cv2.imread(imagePath) writer = PascalVocWriter( imgFolderName, imgFileNameWithoutExt, image_size, localImgPath=imagePath, shape_type=shape_type_) bSave = False for shape in shapes: points = shape['points'] label = shape['label'] if shape['shape_type'] == 0: print 'add rects' bndbox = LabelFile.convertPoints2BndBox(points) writer.addBndBox( bndbox[0], bndbox[1], bndbox[2], bndbox[3], label) if shape['shape_type'] == 1: print 'add polygons' writer.addPolygon(points, label) bSave = True if bSave: writer.save(targetFile=savefilename) return
def savePascalVocFormat(self, filename, shapes, imagePath, imageData, lineColor=None, fillColor=None, databaseSrc=None): imgFolderPath = os.path.dirname(imagePath) imgFolderName = os.path.split(imgFolderPath)[-1] imgFileName = os.path.basename(imagePath) imgFileNameWithoutExt = os.path.splitext(imgFileName)[0] # Read from file path because self.imageData might be empty if saving to # Pascal format print(str(imagePath)) cvImg = cv2.imread(str(imagePath)) height, width, channel = cvImg.shape bytesPerLine = channel * width qImg = QImage(cvImg.data, width, height, bytesPerLine, QImage.Format_RGB888) #image = QImage() #image.load(imagePath) image = qImg imageShape = [ image.height(), image.width(), 1 if image.isGrayscale() else 3 ] writer = PascalVocWriter(imgFolderName, imgFileNameWithoutExt,\ imageShape, localImgPath=imagePath) bSave = False for shape in shapes: points = shape['points'] label = shape['label'] bndbox = LabelFile.convertPoints2BndBox(points) writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], bndbox[3], label) bSave = True if bSave: writer.save(targetFile=filename) return
def save_patches(self, img, objs, patch_name, left, top, right, down): # anno_out = self.anno_out_path / f"{patch_name}.xml" patch_box = np.array([left, top, right, down])[None, :] obj_boxes = np.array([obj["bbox"] for obj in objs]) half_ious, inter_boxes = np_half_iou(obj_boxes, patch_box) half_ious = half_ious.squeeze() inter_boxes = inter_boxes.squeeze() width = right - left height = down - top xml_writer = PascalVocWriter("TianzhiDataset", f'{patch_name}.jpg', (height, width, 3)) for idx, half_iou in enumerate(half_ious): if half_iou >= self.iou_thresh: # print(patch_name, inter_boxes[idx]) new_box = inter_boxes[idx] - np.array([left, top, left, top]) new_box = new_box.astype("int") xml_writer.add_bbox(objs[idx]["name"], False, new_box.tolist()) xml_writer.save(self.anno_out_path / f'{patch_name}.xml') self.save_image_patch(img, patch_name, left, top, width, height)
def savePascalVocFormat(self, filename, shapes, imagePath, imageData, lineColor=None, fillColor=None, databaseSrc=None): imgFolderPath = os.path.dirname(imagePath) imgFolderName = os.path.split(imgFolderPath)[-1] imgFileName = os.path.basename(imagePath) imgFileNameWithoutExt = os.path.splitext(imgFileName)[0] img = cv2.imread(imagePath) imageShape = img.shape writer = PascalVocWriter(imgFolderName, imgFileNameWithoutExt,\ imageShape, localImgPath=imagePath) bSave = False for shape in shapes: points = shape['points'] label = shape['label'] bndbox = LabelFile.convertPoints2BndBox(points) writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], bndbox[3], label) bSave = True if bSave: writer.save(targetFile = filename) return
def savePascalVocFormat(self, filename, shapes, imagePath, imageData, lineColor=None, fillColor=None, databaseSrc=None): imgFolderPath = os.path.dirname(imagePath) imgFolderName = os.path.split(imgFolderPath)[-1] imgFileName = os.path.basename(imagePath) imgFileNameWithoutExt = os.path.splitext(imgFileName)[0] img = cv2.imread(imagePath) imageShape = img.shape writer = PascalVocWriter(imgFolderName, imgFileNameWithoutExt,\ imageShape, localImgPath=imagePath) bSave = True #False to block annotations without bounding boxes for shape in shapes: points = shape['points'] label = shape['label'] bndbox = LabelFile.convertPoints2BndBox(points) writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], bndbox[3], label) bSave = True if bSave: writer.save(targetFile = filename) return
def test_upper(self): dir_name = os.path.abspath(os.path.dirname(__file__)) libs_path = os.path.join(dir_name, '..', 'libs') sys.path.insert(0, libs_path) from pascal_voc_io import PascalVocWriter from pascal_voc_io import PascalVocReader # Test Write/Read writer = PascalVocWriter('tests', 'test', (512, 512, 1), localImgPath='tests/test.bmp') difficult = 1 writer.addBndBox(60, 40, 430, 504, 'person', difficult) writer.addBndBox(113, 40, 450, 403, 'face', difficult) writer.save('tests/test.xml') reader = PascalVocReader('tests/test.xml') shapes = reader.getShapes() personBndBox = shapes[0] face = shapes[1] self.assertEqual(personBndBox[0], 'person') self.assertEqual(personBndBox[1], [(60, 40), (430, 40), (430, 504), (60, 504)]) self.assertEqual(face[0], 'face') self.assertEqual(face[1], [(113, 40), (450, 40), (450, 403), (113, 403)])
def savePascalVocFormat(self, filename, shapes, imagePath, imageData, lineColor=None, fillColor=None, databaseSrc=None): imgFolderPath = os.path.dirname(imagePath) imgFolderName = os.path.split(imgFolderPath)[-1] imgFileName = os.path.basename(imagePath) imgFileNameWithoutExt = os.path.splitext(imgFileName)[0] # Read from file path because self.imageData might be empty if saving to # Pascal format image = QImage() image.load(imagePath) imageShape = [image.height(), image.width(), 1 if image.isGrayscale() else 3] writer = PascalVocWriter(imgFolderName, imgFileNameWithoutExt,\ imageShape, localImgPath=imagePath) bSave = False for shape in shapes: points = shape['points'] label = shape['label'] bndbox = LabelFile.convertPoints2BndBox(points) writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], bndbox[3], label) bSave = True if bSave: writer.save(targetFile = filename) return
def SaveCurrent(self): xmin = int(self.Scene.roiCoord[0] - self.EffectRect[0]) ymin = int(self.Scene.roiCoord[1] - self.EffectRect[1]) xmax = int(self.Scene.roiCoord[2] + xmin) ymax = int(self.Scene.roiCoord[3] + ymin) if xmin >= 0 and ymin >= 0 and xmax <= self.EffectRect[ 2] and ymax <= self.EffectRect[3]: name_str = self.SaveName + ("%03d" % self.FrameIdx) crop_img = self.CurrentFrame[ self.EffectRect[1]:self.EffectRect[1] + self.EffectRect[3], self.EffectRect[0]:self.EffectRect[0] + self.EffectRect[2]] cv2.imwrite(self.SavePath + "JPEGImages\\" + name_str + ".jpg", crop_img) labelFile = PascalVocWriter( "BP2017", name_str + ".jpg", (self.EffectRect[2], self.EffectRect[3], 3)) labelFile.addBndBox(xmin, ymin, xmax, ymax, self.ClassComboBox.currentText(), self.SavePose, False) labelFile.save(targetFile=self.SavePath + "Annotations\\" + name_str + ".xml") self.TagInfo.append(name_str) else: self.MsgInfo.append("-> Out of the effect region!")
image.height(), image.width(), 1 if image.isGrayscale() else 3 ] imgFolderName = os.path.basename(imgFolderPath) imgFileName = os.path.basename(imagePath) writer = PascalVocWriter(imgFolderName, imgFileName, imageShape, localImgPath=imagePath) # Read YOLO file txtPath = imgFolderPath + "/Label/" + annotation_no_txt + '.txt' #print(txtPath) tOIDParseReader = OIDReader(txtPath) shapes = tOIDParseReader.getShapes() #print(shapes) for shape in shapes: label = shape[0] xmin = shape[1] ymin = shape[2] x_max = shape[3] y_max = shape[4] writer.addBndBox(xmin, ymin, x_max, y_max, label, 0) writer.save(targetFile=imgFolderPath + "/" + annotation_no_txt + ".xml")
import os img_path='/media/wac/backup1/test_ssd/background/' save_path='/media/wac/backup1/test_ssd/tmp' R=re.compile('(\.jpg|\.jpeg|\.bmp|\.png|\.JPG)$') for root,dirs ,files in os.walk(img_path): if len(files) == 0: continue for filename in files: if R.search(filename) !=None: abspath=os.path.join(root,filename) label=root.split('/')[-1] path=os.path.join(save_path,label) if not os.path.exists(path): os.mkdir(path) img=load_img(abspath) img=img_to_array(img) writer = PascalVocWriter('tests', filename[:-4], img.shape, localImgPath=abspath) difficult = 0 name='background' writer.addBndBox(0, 0, img.shape[1],img.shape[0] , name, difficult) savename=os.path.join(path,filename) savename=savename[:-4] print savename writer.save('{}.xml'.format(str(savename)))
filename = path + file print file dot = file.find('.') purename = file[:dot] reader = PascalVocReader(filename) reader.parseXML() boxes = [] for i, shape in enumerate(reader.shapes): if i < (len(reader.shapes) / 2): boxes.append(shape) boxes = sorted(boxes, key=lambda item: item[1][0][0]) readimgname = 'VOCdevkit/VOC2050/JPEGImages/{}.jpg'.format(purename) img = cv2.imread(readimgname) imgSize = [img.shape[0], img.shape[1], 1] foldername = 'JPEGImages' filename = purename + '.jpg' localImagePath = '/root/darknet/scripts/VOCdevkit/VOC2050back/JPEGImages/' + filename writer = PascalVocWriter(foldername, filename, imgSize, localImgPath=localImagePath) #print type(boxes) for b in boxes: writer.addBndBox(b[1][0][0], b[1][0][1], b[1][2][0], b[1][2][1], b[0], 0) #print b writer.verified = False xmlfname = '/root/darknet/scripts/VOCdevkit/VOC2050back/Annotations/{}'.format( file) writer.save(xmlfname)
from unittest import TestCase import sys import os dir_name = os.path.abspath(os.path.dirname(__file__)) libs_path = os.path.join(dir_name, '..', 'libs') sys.path.insert(0, libs_path) from pascal_voc_io import PascalVocWriter from pascal_voc_io import PascalVocReader # Test Write/Read writer = PascalVocWriter('tests', 'test', (512, 512, 1), localImgPath='tests/test.bmp') difficult = 1 writer.addBndBox(60, 40, 430, 504, 'person', difficult) writer.addBndBox(113, 40, 450, 403, 'face', difficult) writer.save('tests/test.xml') reader = PascalVocReader('tests/test.xml') shapes = reader.getShapes()
imgdir = 'imgs' anndir = 'anns' setdir = 'sets' imgs_basename_fullname = [[os.path.splitext(p)[0], p] for p in os.listdir(os.path.join(workdir, imgdir))] anns_basename = set([ os.path.splitext(p)[0] for p in os.listdir(os.path.join(workdir, anndir)) ]) need_del_id = [] for i, k in enumerate(imgs_basename_fullname): if k[0] in anns_basename: need_del_id.append(i) for i in sorted(need_del_id)[::-1]: del imgs_basename_fullname[i] print('Need process ' + str(len(imgs_basename_fullname)) + ' files') for basename_fullname in imgs_basename_fullname: basename, fullname = basename_fullname print(fullname) img = imageio.imread(os.path.join(workdir, imgdir, fullname)) w = PascalVocWriter(imgdir, fullname, img.shape) w.save(os.path.join(workdir, anndir, basename + '.xml')) print('complete')
image.load(imagePath) imageShape = [ image.height(), image.width(), 1 if image.isGrayscale() else 3 ] imgFolderName = os.path.basename(imgFolderPath) imgFileName = os.path.basename(imagePath) writer = PascalVocWriter(imgFolderName, imgFileName, imageShape, localImgPath=imagePath) # Read YOLO file txtPath = imgFolderPath + "/" + file tYoloParseReader = YoloReader(txtPath, image) shapes = tYoloParseReader.getShapes() num_of_box = len(shapes) for i in range(num_of_box): label = shapes[i][0] xmin = shapes[i][1][0][0] ymin = shapes[i][1][0][1] x_max = shapes[i][1][2][0] y_max = shapes[i][1][2][1] writer.addBndBox(xmin, ymin, x_max, y_max, label, 0) writer.save(targetFile=imgOutputPath + "/" + annotation_no_txt + ".xml")
## ## color manipulation on entire result h, s, v = cv2.split(cv2.cvtColor(res, cv2.COLOR_RGB2HSV)) random_hue = np.random.random_integers(-10, 10) h_min = random_hue + np.min(h) h_max = random_hue + np.max(h) if h_min < 0 or h_max > 255: random_hue = 0 h = (h + random_hue) s /= np.random.random_integers(1, 2) v /= np.random.random_integers(1, 2) res = cv2.cvtColor(cv2.merge((h, s, v)), cv2.COLOR_HSV2RGB) ## cv2.imwrite(image_file_path, res) labelWriter.save(targetFile=xml_file_path) counter = counter + 1 #print ("COUNTER: "+str(counter)) except Exception as e: print("Something went wrong: {} - continue anyway...".format(e)) ## done - delete variables sample_paths = None samples = None bg_paths = None backgrounds = None ## generate tf record if selected if generate_tf: tsd = TSDTFLabeledDataProvider(output_dir, split=tf_split) tsd.create_tfrecord()