Ejemplo n.º 1
0
    def saveLabels(self, filePath):
        lf = LabelFile()

        def format_shape(s):
            return dict(label=s.label,
                        line_color=s.line_color.getRgb()\
                                if s.line_color != self.lineColor else None,
                        fill_color=s.fill_color.getRgb()\
                                if s.fill_color != self.fillColor else None,
                        points=[(p.x(), p.y()) for p in s.points])

        shapes = [format_shape(shape) for shape in self.canvas.shapes]
        # Can add differrent annotation formats here
        try:
            unicodeFilePath = u(filePath)
            if self.usingPascalVocFormat is True:
                lf.savePascalVocFormat(unicodeFilePath, shapes,
                                       unicodeFilePath, self.imageData,
                                       self.lineColor.getRgb(),
                                       self.fillColor.getRgb())
            else:
                lf.save(unicodeFilePath, shapes, unicodeFilePath,
                        self.imageData, self.lineColor.getRgb(),
                        self.fillColor.getRgb())
                self.labelFile = lf
                self.filePath = unicodeFilePath
            return True
        except LabelFileError as e:
            self.errorMessage(u'Error saving label data', u'<b>%s</b>' % e)
            return False
Ejemplo n.º 2
0
    def load_wpif(self, dataset_dir):
        """Load a subset of the COCO dataset.
        dataset_dir: The root directory of the dataset.
        """

        # get all labeled json file under dataset
        examples_list = []
        for example in os.listdir(dataset_dir):
            if example[-5:] == '.json':
                examples_list.append(os.path.join(dataset_dir, example))

        # Add classes
        self.add_class("WPIF", self.class_names.index('pad'), 'pad')

        for example_name in examples_list:
            label_file = LabelFile()
            label_file.load(example_name, dataset_dir)
            # Add images
            image_path = label_file.imagePath
            image_name = os.path.split(image_path)[-1]
            image_id = int(image_name.split('.')[0][6:12])
            width = label_file.width
            height = label_file.height
            annotations = []
            for label, points, line_color, fill_color in label_file.shapes:
                annotations.append([label, points])
            self.add_image("WPIF", image_id=image_id,
                           path=image_path,
                           width=width, height=height,
                           annotations=annotations)
Ejemplo n.º 3
0
    def saveLabels(self, annotationFilePath):
        annotationFilePath = ustr(annotationFilePath)
        if self.labelFile is None:
            self.labelFile = LabelFile()
            self.labelFile.verified = self.canvas.verified

        def format_shape(s):
            return dict(label=s.label,
                        line_color=s.line_color.getRgb()
                        if s.line_color != self.lineColor else None,
                        fill_color=s.fill_color.getRgb()
                        if s.fill_color != self.fillColor else None,
                        points=[(p.x(), p.y()) for p in s.points],
                       # add chris
                        difficult = s.difficult)

        shapes = [format_shape(shape) for shape in self.canvas.shapes]
        # Can add differrent annotation formats here
        try:
            if self.usingPascalVocFormat is True:
                print ('Img: ' + self.filePath +
                       ' -> Its xml: ' + annotationFilePath)
                self.labelFile.savePascalVocFormat(annotationFilePath, shapes, self.filePath, self.imageData,
                                                   self.lineColor.getRgb(), self.fillColor.getRgb())
            else:
                self.labelFile.save(annotationFilePath, shapes, self.filePath, self.imageData,
                                    self.lineColor.getRgb(), self.fillColor.getRgb())
            return True
        except LabelFileError as e:
            self.errorMessage(u'Error saving label data',
                              u'<b>%s</b>' % e)
            return False
Ejemplo n.º 4
0
 def loadFile(self, filename=None):
     """Load the specified file, or the last opened file if None."""
     self.resetState()
     self.canvas.setEnabled(False)
     if filename is None:
         filename = self.settings.get('filename', '')
     filename = str(filename)
     if QFile.exists(filename):
         if LabelFile.isLabelFile(filename):
             try:
                 self.labelFile = LabelFile(filename)
                 # FIXME: PyQt4 installed via Anaconda fails to load JPEG
                 # and JSON encoded images.
                 # https://github.com/ContinuumIO/anaconda-issues/issues/131
                 if QImage.fromData(self.labelFile.imageData).isNull():
                     raise LabelFileError(
                         'Failed loading image data from label file.\n'
                         'Maybe this is a known issue of PyQt4 built on'
                         ' Anaconda, and may be fixed by installing PyQt5.')
             except LabelFileError as e:
                 self.errorMessage('Error opening file',
                         ("<p><b>%s</b></p>"
                          "<p>Make sure <i>%s</i> is a valid label file.")\
                         % (e, filename))
                 self.status("Error reading %s" % filename)
                 return False
             self.imageData = self.labelFile.imageData
             self.lineColor = QColor(*self.labelFile.lineColor)
             self.fillColor = QColor(*self.labelFile.fillColor)
         else:
             # Load image:
             # read data first and store for saving into label file.
             self.imageData = read(filename, None)
             self.labelFile = None
         image = QImage.fromData(self.imageData)
         if image.isNull():
             formats = ['*.{}'.format(fmt.data().decode())
                        for fmt in QImageReader.supportedImageFormats()]
             self.errorMessage(
                 'Error opening file',
                 '<p>Make sure <i>{0}</i> is a valid image file.<br/>'
                 'Supported image formats: {1}</p>'
                 .format(filename, ','.join(formats)))
             self.status("Error reading %s" % filename)
             return False
         self.status("Loaded %s" % os.path.basename(str(filename)))
         self.image = image
         self.filename = filename
         self.canvas.loadPixmap(QPixmap.fromImage(image))
         if self.labelFile:
             self.loadLabels(self.labelFile.shapes)
         self.setClean()
         self.canvas.setEnabled(True)
         self.adjustScale(initial=True)
         self.paintCanvas()
         self.addRecentFile(self.filename)
         self.toggleActions(True)
         return True
     return False
Ejemplo n.º 5
0
    def saveLabels(self, filename):
        lf = LabelFile()
        def format_shape(s):
            return dict(label=str(s.label),
                        line_color=s.line_color.getRgb()\
                                if s.line_color != self.lineColor else None,
                        fill_color=s.fill_color.getRgb()\
                                if s.fill_color != self.fillColor else None,
                        points=[(p.x(), p.y()) for p in s.points])

        shapes = [format_shape(shape) for shape in self.canvas.shapes]
        try:
            lf.save(filename, shapes, str(self.filename), self.imageData,
                self.lineColor.getRgb(), self.fillColor.getRgb())
            self.labelFile = lf
            self.filename = filename
            return True
        except LabelFileError as e:
            self.errorMessage('Error saving label data',
                    '<b>%s</b>' % e)
            return False
Ejemplo n.º 6
0
    def loadFile(self, filePath=None):
        """Load the specified file, or the last opened file if None."""
        self.resetState()
        self.canvas.setEnabled(False)
        if filePath is None:
            filePath = self.settings.get('filename')

        unicodeFilePath = u(filePath)
        # Tzutalin 20160906 : Add file list and dock to move faster
        # Highlight the file item
        if unicodeFilePath and self.fileListWidget.count() > 0:
            index = self.mImgList.index(unicodeFilePath)
            fileWidgetItem = self.fileListWidget.item(index)
            fileWidgetItem.setSelected(True)

        if unicodeFilePath and os.path.exists(unicodeFilePath):
            if LabelFile.isLabelFile(unicodeFilePath):
                try:
                    self.labelFile = LabelFile(unicodeFilePath)
                except LabelFileError as e:
                    self.errorMessage(u'Error opening file',
                                      (u"<p><b>%s</b></p>"
                                       u"<p>Make sure <i>%s</i> is a valid label file.") \
                                      % (e, unicodeFilePath))
                    self.status("Error reading %s" % unicodeFilePath)
                    return False
                self.imageData = self.labelFile.imageData
                self.lineColor = QColor(*self.labelFile.lineColor)
                self.fillColor = QColor(*self.labelFile.fillColor)
            else:
                # Load image:
                # read data first and store for saving into label file.
                self.imageData = read(unicodeFilePath, None)
                self.labelFile = None
            image = QImage.fromData(self.imageData)
            if image.isNull():
                self.errorMessage(
                    u'Error opening file',
                    u"<p>Make sure <i>%s</i> is a valid image file." %
                    unicodeFilePath)
                self.status("Error reading %s" % unicodeFilePath)
                return False
            self.status("Loaded %s" % os.path.basename(unicodeFilePath))
            self.image = image
            self.filePath = unicodeFilePath
            self.canvas.loadPixmap(QPixmap.fromImage(image))
            if self.labelFile:
                self.loadLabels(self.labelFile.shapes)
            self.setClean()
            self.canvas.setEnabled(True)
            self.adjustScale(initial=True)
            self.paintCanvas()
            self.addRecentFile(self.filePath)
            self.toggleActions(True)

            ## Label xml file and show bound box according to its filename
            if self.usingPascalVocFormat is True and \
                            self.defaultSaveDir is not None:
                basename = os.path.basename(
                    os.path.splitext(self.filePath)[0]) + XML_EXT
                xmlPath = os.path.join(self.defaultSaveDir, basename)
                self.loadPascalXMLByFilename(xmlPath)

            return True
        return False