Example #1
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.512.512.bmp')
        difficult = 1
        truncated = 1
        writer.addBndBox(60, 40, 430, 504, 'person', difficult, truncated)
        writer.addBndBox(113, 40, 450, 403, 'face', difficult, truncated)
        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)])
Example #2
0
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)
Example #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, 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
Example #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
Example #5
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)
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)
Example #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')
Example #8
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

        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
Example #9
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'))
Example #10
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)  #获取文件名(包含文件扩展名,即形如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
Example #11
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
Example #12
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")
Example #13
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
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")))
Example #15
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
Example #16
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
Example #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]

        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
Example #18
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)])
Example #19
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!")
Example #20
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
Example #21
0
            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")
Example #22
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()
Example #23
0
    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)
        bndbox = [xmin, ymin, xmax, ymax]
        writer.addBndBox(bndbox[0], bndbox[1], bndbox[2], bndbox[3], 0, 0)

    writer.save(targetFile=imgFileName[:len(imgFileName) - 4] + ".xml")
    cv.imwrite(outputpath + "\\" + imgFileName[:len(imgFileName) - 4] + ".jpg",
               img)
Example #24
0
         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)
 # Exit if ESC pressed
 k = cv2.waitKey(1) & 0xff
 if k == 27 or k == 'q':
Example #25
0
                            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)


Example #26
0
                if shape.intersects(s):
                    is_valid_shape = False
                    break

            if is_valid_shape:
                #print ("add shape for label:" + label_name)
                shapes.append(shape)
                res = transparentOverlay(res,
                                         object_sample,
                                         pos=pos,
                                         scale=1,
                                         alpha_v=min_object_transparancy +
                                         random_alpha)
                labelWriter.addBndBox(xmin=x1,
                                      ymin=y1,
                                      xmax=x2,
                                      ymax=y2,
                                      name=label_name,
                                      difficult=0)
                shape = None
                samples_map[label_name] = samples_map[label_name] + 1
                continue
            else:
                #print("overlapping "+str(shape))
                shape = None
                break

            #print("shapes: "+str(len(shapes)))
        ## apply convolutioons once on result image
        number_filters = np.random.random_integers(
            0, max_number_filter_apps_on_background)
        count_filter_apps = 0
Example #27
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
    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
Example #30
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)
Example #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)))