Exemplo n.º 1
0
    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)
Exemplo n.º 2
0
def savePascalVocFormat(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 = cv2.imread(imagePath)
        imageW, imageH = image.shape[:2]
        imageShape = [imageH, imageW]
        writer = PascalVocWriter(imgFolderName, imgFileName,
                                 imageShape, localImgPath=imagePath)

        for shape in shapes:
            difficult = 0
            bndbox, label = shape
            xmin = bndbox[0]
            ymin = bndbox[1]
            xmax = xmin + bndbox[2]
            ymax = ymin + bndbox[3]
            writer.addBndBox(xmin, ymin, xmax, ymax, label, difficult)

        writer.save(targetFile=filename)
        return
Exemplo n.º 3
0
    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, imgFileName, imageShape)
        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
Exemplo n.º 4
0
    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
Exemplo n.º 5
0
    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
Exemplo n.º 6
0
    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
Exemplo n.º 7
0
 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')
Exemplo n.º 8
0
    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
Exemplo n.º 9
0
    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)
        #print(imgFileName)
        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)

        writer.save(targetFile=filename)
        return
Exemplo n.º 10
0
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'))
Exemplo n.º 11
0
    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
Exemplo n.º 12
0
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 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.512.512.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 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")))
Exemplo n.º 15
0
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")
Exemplo n.º 16
0
    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)])
Exemplo n.º 17
0
    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
Exemplo n.º 18
0
    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
Exemplo n.º 19
0
    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)
Exemplo n.º 20
0
 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!")
Exemplo n.º 21
0
        _, _= im_detect(net, im)

    im_names = os.listdir(input_dir+"/img")

    for im_name in im_names:
        print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        print "auto label {0}".format(im_name)
        im_file = os.path.join(input_dir, 'img', im_name)

        label_file = os.path.join(input_dir, 'annotation', im_name)
        index = label_file.rindex('.')
        label_file = label_file[:index] + ".xml"
        if os.path.isfile(label_file):
            tmp_reader = PascalVocReader(label_file)
            size = tmp_reader.getSize()
            tmp_writer = PascalVocWriter(input_dir, im_name, size)
            shapes = tmp_reader.getShapes()
            for i in shapes:
                tmp_writer.addBndBox(i[1][0][0], i[1][0][1], i[1][2][0], i[1][2][1], i[0])
            print "load {0} labels from {1}".format(len(shapes), label_file)
        else:
            print "can not find label file {0}".format(label_file)
            size = cv2.imread(im_file).shape
            tmp_writer = PascalVocWriter(input_dir, im_name, size)
        
        n = auto_label(net, im_file, tmp_writer)
        
        tmp_writer.save(output_dir + '/' + os.path.basename(label_file))
        print "auto label {0} labels".format(n)
    plt.show()
Exemplo n.º 22
0
    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
Exemplo n.º 23
0
filepath = "NFPAdataset"
outputpath = "OutputImages"
outputlabel = "OutputLabels"
for filename in glob.glob(os.path.join(filepath, '*.txt')):
    f = open(filename, "r")
    im = Image.open(filename[:len(filename) - 4] + ".jpg")
    img = cv.imread(filename[:len(filename) - 4] + ".jpg")

    imgFolderPath = filepath
    imgFolderName = os.path.split(imgFolderPath)[-1]
    imgFileName = os.path.basename(filename[:len(filename) - 4] + ".jpg")
    imagePath = filename[:len(filename) - 4] + ".jpg"
    imageShape = [int(im.size[0]), int(im.size[1]), 3]

    writer = PascalVocWriter(imgFolderName,
                             imgFileName,
                             imageShape,
                             localImgPath=imagePath)

    for line in f:
        cord = line.split()
        x = float(cord[1])
        y = float(cord[2])
        w = float(cord[3])
        h = float(cord[4])
        s0 = int(im.size[0])
        s1 = int(im.size[1])
        xmax = (int)((s0 * (2 * x + w)) / 2)
        xmin = (int)((s0 * (2 * x - w)) / 2)
        ymax = (int)((s1 * (2 * y + h)) / 2)
        ymin = (int)((s1 * (2 * y - h)) / 2)
        img = cv.rectangle(img, (xmin, ymin), (xmax, ymax), (0, 0, 255), 4)
Exemplo n.º 24
0
     try:
         p1 = (int(bbox[0]), int(bbox[1]))
         p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))
         cv2.rectangle(frame, p1, p2, (255, 0, 0), 2, 1)
         # cv2.imshow('test',frame)
         cv2.setMouseCallback("Tracking", MouseEventCallBack)
         track_state_is_normal = True
         # Initialize tracker with first frame and bounding box
         ok = tracker.init(frame, bbox)
     except:
         continue
 # imageShape = [frame.height, frame.width, 3]
 imageShape = image.shape
 imgFolderName = output_dir
 imgFileName = os.path.split(video_path)[-1].split('.')[0] + '_frame_' + str(i) + '.png'
 writer = PascalVocWriter(imgFolderName, imgFileName, imageShape)
 writer.verified = False
 # try:
 writer.addBndBox(int(p1[0]), int(p1[1]), int(p2[0]), int(p2[1]), '1', 0)
 targetPath = '{}_frame_{:08}'.format(os.path.join(output_dir, os.path.split(video_path)[-1].split('.')[0]), i)
 targetFile = targetPath + '.xml'
 targetImage = targetPath + '.png'
 writer.save(targetFile)
 result=cv2.imwrite(targetImage, image)
 print(targetImage,result)
 # Display tracker type on frame
 cv2.putText(frame, " Tracker", (100, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50, 170, 50), 2)
 # Display FPS on frame
 cv2.putText(frame, "FPS : " + str(int(fps)), (100, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50, 170, 50), 2);
 # Display result
 cv2.imshow("Tracking", frame)
Exemplo n.º 25
0
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')
Exemplo n.º 26
0
     str(counter) + " of " + str(number_sample_images) +
     " samples generated..")
 background = backgrounds[np.random.random_integers(
     0,
     len(backgrounds) - 1)]
 background = cv2.resize(background, output_image_size_wh,
                         cv2.INTER_CUBIC)
 image_size = background.shape
 file_path = output_dir.as_posix()
 file_name = "generated_" + str(binascii.hexlify(os.urandom(16)))
 xml_file_name = file_name + ".xml"
 image_file_name = file_name + ".jpeg"
 xml_file_path = file_path + "/" + xml_file_name
 image_file_path = file_path + "/" + image_file_name
 labelWriter = PascalVocWriter(foldername=output_dir.name,
                               imgSize=image_size,
                               filename=image_file_name,
                               localImgPath=image_file_path)
 res = background.copy()
 shapes = []
 num_samples_per_img = np.random.random_integers(
     1, max_samples_per_image)
 while len(shapes) < num_samples_per_img:
     ## transform sample
     sample_index = np.random.random_integers(0,
                                              len(samples) - 1)
     object_sample = samples[sample_index][0].copy()
     label_name = samples[sample_index][1]
     label_name = label_name.split('.')[0]
     if label_name not in samples_map.keys():
         samples_map[label_name] = 0
         print("New Stats for {}".format(label_name))
Exemplo n.º 27
0
                        iou = maxIou(x1 + 0.5 * w1, y1 + 0.5 * h1, w1, h1, x2 + 0.5 * w2, y2 + 0.5 * h2, w2, h2)
                        if iou < 0.1:
                            continue
                            # print '没有重叠,过滤掉'
                        elif iou > 0.5:
                            # print '两个bounding box重叠度为:', iou
                            # print '将舍弃该张图像'
                            continue




                        imgFileName = os.path.basename(background_imgs[i])[:-4] + "-" + os.path.basename(roi_imgs[j])[:-4] + "-" + str(j_angle) + "-" + os.path.basename(roi_imgs[k][:-4]) + "-" + str(k_angle) + ".png"
                        imagePath = os.path.join(imgFolderName, imgFileName)
                        writer = PascalVocWriter(imgFolderName, imgFileName, (img_h, img_w, 3), localImgPath=imagePath,
                                                 usrname="auto")
                        writer.verified = True
                        writer.addBndBox(x1, y1, x1 + w1, y1 + h1, label_1, 0)
                        writer.addBndBox(x2, y2, x2 + w2, y2 + h2, label_2, 0)
                        writer.save(targetFile=imagePath[:-4] + XML_EXT)

                        if np.random.randint(1 , 11) == 10:
                            result4 = addPepperNoise(result4)
                        if np.random.randint(1 , 6) == 3:
                            result4 = cv2.GaussianBlur(result4 , (5 , 5) , 0)


                        cv2.imwrite(imagePath, result4)

    cv2.waitKey(0)
Exemplo n.º 28
0
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()
                #print '======================'
                for c in range(3):
                    if tmpimg[i, j][c] * a + b > 255:
                        dst[i, j][c] = tmpimg[i, j][c]
                        #print 'a'
                    elif tmpimg[i, j][c] * a + b < 0:
                        dst[i, j][c] = tmpimg[i, j][c]
                        #print 'b'
                    else:
                        dst[i, j][c] = tmpimg[i, j][c] * a + b
                        #print 'c'
                        #print a
                    #print str(dst[i, j][c])+"/"+str(tmpimg[i, j][c])

        img[y0:y1, x0:x1] = dst
    imgSize = [img.shape[0], img.shape[1], 1]
    localImagePath = '/root/darknet/scripts/VOCdevkit/VOC2050_corrected/JPEGImages/' + newname + '.jpg'
    newxmlfname = '/root/darknet/scripts/VOCdevkit/VOC2050_corrected/Annotations/' + newname + '.xml'
    writer = PascalVocWriter(foldername,
                             newname + '.jpg',
                             imgSize,
                             localImgPath=localImagePath)
    writer.verified = False
    for i, shape in enumerate(reader.shapes):
        if i < (len(reader.shapes) / 2):
            writer.addBndBox(shape[1][0][0], shape[1][0][1], shape[1][2][0],
                             shape[1][2][1], shape[0], 0)
    writer.save(newxmlfname)
    cv2.imwrite(goal_dir + newname + '.jpg', img)
    print goal_dir + newname
Exemplo n.º 30
0
    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]
        imgFileNameWithoutExt = imgFileName
        # 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
        # LOGIC st
        bkg_im_w = image.width()
        bkg_im_h = image.height()
        bkg_im_w_2 = bkg_im_w - 2
        bkg_im_h_2 = bkg_im_h - 2
        # LOGIC ed
        for shape in shapes:
            points = shape['points']
            label = shape['label']
            bndbox = LabelFile.convertPoints2BndBox(points)

            bnd_0 = bndbox[0]
            bnd_1 = bndbox[1]
            bnd_2 = bndbox[2]
            bnd_3 = bndbox[3]

            if 2 > bnd_0:
                bnd_0 = 2
            if 2 > bnd_1:
                bnd_1 = 2
            if bkg_im_w_2 < bnd_2:
                bnd_2 = bkg_im_w_2
            if bkg_im_h_2 < bnd_3:
                bnd_3 = bkg_im_h_2

            if bnd_0 >= bnd_2:
                continue
            if bnd_1 > bnd_3:
                continue

            writer.addBndBox(bnd_0, bnd_1, bnd_2, bnd_3, label)
            bSave = True
            # LOGIC ed

        if bSave:
            writer.save(targetFile=filename)
        return
Exemplo n.º 31
0
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)))

Exemplo n.º 32
0
        annotation_no_txt = os.path.splitext(file)[0]

        imagePath = imgFolderPath + "/" + annotation_no_txt + ".jpg"

        image = QImage()
        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 + "/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]
Exemplo n.º 33
0
    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)