Esempio n. 1
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.labelList.shapes]
        try:
            imagePath = os.path.relpath(self.imagePath,
                                        os.path.dirname(filename))
            imageData = self.imageData if self._config['store_data'] else None
            lf.save(filename, shapes, imagePath, imageData,
                    self.lineColor.getRgb(), self.fillColor.getRgb(),
                    self.otherData)
            self.labelFile = lf
            # disable allows next and previous image to proceed
            # self.filename = filename
            return True
        except LabelFileError as e:
            self.errorMessage('Error saving label data', '<b>%s</b>' % e)
            return False
Esempio n. 2
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.labelList.shapes]
        try:
            imagePath = os.path.relpath(
                self.imagePath, os.path.dirname(filename))
            imageData = self.imageData if self._config['store_data'] else None
            pixmap = QtGui.QPixmap.fromImage(self.image)
            imgHeight = pixmap.height()
            imgWidth = pixmap.width()
            lf.save(filename, shapes, imagePath, imageData,imgHeight,imgWidth,
                    self.lineColor.getRgb(), self.fillColor.getRgb(),
                    self.otherData)
            self.labelFile = lf
            # disable allows next and previous image to proceed
            # self.filename = filename
            return True
        except LabelFileError as e:
            self.errorMessage('Error saving label data', '<b>%s</b>' % e)
            return False
Esempio n. 3
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
Esempio n. 4
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]

        of_txt = filename.replace(".json", '.txt')
        of_txt = of_txt.replace(".jpg", '.txt')
        of_txt = of_txt.replace(".png", '.txt')
        of_dir = os.path.dirname(of_txt)
        if self.an is not None and self.an.is3Pts:
            of_txt = '{0}/{1}'.format(of_dir, os.path.basename(of_txt))
            of_txt = open(of_txt, 'w')
            for shape in shapes:
                center = [0, 0]
                for point in shape['points']:
                    center[0] += point[0]
                    center[1] += point[1]

                radius = (shape[1][0] - shape[0][0]) / 2
                of_txt.write('{0} {1} {2}\n'.format(center[0] / 4,
                                                    center[1] / 4, radius))

            of_txt.close()

        else:
            of_txt = '{0}/gt_{1}'.format(of_dir, os.path.basename(of_txt))
            of_txt = open(of_txt, 'w')
            for shape in shapes:
                for point in shape['points']:
                    of_txt.write('{0},{1},'.format(point[0], point[1]))
                of_txt.write('1, {0}\n'.format(shape['label']))
            of_txt.close()

        return True

        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
Esempio n. 5
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
Esempio n. 6
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)
             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():
             self.errorMessage('Error opening file',
                     "<p>Make sure <i>%s</i> is a valid image file." % filename)
             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
Esempio n. 7
0
    def saveLabels(self, filename):
        lf = LabelFile()
        def format_shape(s):
            return dict(label=str(s.label),
                        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
Esempio n. 8
0
    def saveLabels(self, filename):
        lf = LabelFile()

        def format_shape(s):
            return dict(label=str(s.label),
                        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
Esempio n. 9
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:
            imagePath = os.path.relpath(
                self.imagePath, os.path.dirname(filename))
            imageData = self.imageData if self._store_data else None
            lf.save(filename, shapes, imagePath, 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
Esempio n. 10
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:
            imagePath = os.path.relpath(
                self.imagePath, os.path.dirname(filename))
            imageData = self.imageData if self._store_data else None
            lf.save(filename, shapes, imagePath, imageData,
                self.lineColor.getRgb(), self.fillColor.getRgb())
            self.labelFile = lf
            # self.filename = filename # disable allows next and previous image to proceed
            return True
        except LabelFileError as e:
            self.errorMessage('Error saving label data',
                    '<b>%s</b>' % e)
            return False
Esempio n. 11
0
    def loadFile(self, filename=None):
        """Load the specified file, or the last opened file if None."""
        # changing fileListWidget loads file
        if (filename in self.imageList and self.fileListWidget.currentRow() !=
                self.imageList.index(filename)):
            self.fileListWidget.setCurrentRow(self.imageList.index(filename))
            return

        self.resetState()
        self.canvas.setEnabled(False)
        if filename is None:
            filename = self.settings.value('filename', '')
        filename = str(filename)
        if not QtCore.QFile.exists(filename):
            self.errorMessage('Error opening file',
                              'No such file: <b>%s</b>' % filename)
            return False
        # assumes same name, but json extension
        self.status("Loading %s..." % os.path.basename(str(filename)))
        label_file = os.path.splitext(filename)[0] + '.json'
        if QtCore.QFile.exists(label_file) and \
                LabelFile.isLabelFile(label_file):
            try:
                self.labelFile = LabelFile(label_file)
                # FIXME: PyQt4 installed via Anaconda fails to load JPEG
                # and JSON encoded images.
                # https://github.com/ContinuumIO/anaconda-issues/issues/131
                if QtGui.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, label_file))
                self.status("Error reading %s" % label_file)
                return False
            self.imageData = self.labelFile.imageData
            self.imagePath = os.path.join(os.path.dirname(label_file),
                                          self.labelFile.imagePath)
            self.lineColor = QtGui.QColor(*self.labelFile.lineColor)
            self.fillColor = QtGui.QColor(*self.labelFile.fillColor)
            self.otherData = self.labelFile.otherData
        else:
            # Load image:
            # read data first and store for saving into label file.
            self.imageData = read(filename, None)
            if self.imageData is not None:
                # the filename is image not JSON
                self.imagePath = filename
            self.labelFile = None
        image = QtGui.QImage.fromData(self.imageData)
        if image.isNull():
            formats = [
                '*.{}'.format(fmt.data().decode())
                for fmt in QtGui.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.image = image
        self.filename = filename
        self.canvas.loadPixmap(QtGui.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)
        self.status("Loaded %s" % os.path.basename(str(filename)))
        return True
Esempio n. 12
0
    def loadFile(self, filename=None):
        """Load the specified file, or the last opened file if None."""
        # changing fileListWidget loads file
        if (filename in self.imageList and
                self.fileListWidget.currentRow() !=
                self.imageList.index(filename)):
            self.fileListWidget.setCurrentRow(self.imageList.index(filename))
            return

        self.resetState()
        self.canvas.setEnabled(False)
        if filename is None:
            filename = self.settings.value('filename', '')
        filename = str(filename)
        if not QtCore.QFile.exists(filename):
            self.errorMessage(
                'Error opening file', 'No such file: <b>%s</b>' % filename)
            return False
        # assumes same name, but json extension
        self.status("Loading %s..." % os.path.basename(str(filename)))
        label_file = os.path.splitext(filename)[0] + '.json'
        if QtCore.QFile.exists(label_file) and \
                LabelFile.isLabelFile(label_file):
            try:
                self.labelFile = LabelFile(label_file)
                # FIXME: PyQt4 installed via Anaconda fails to load JPEG
                # and JSON encoded images.
                # https://github.com/ContinuumIO/anaconda-issues/issues/131
                if QtGui.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, label_file))
                self.status("Error reading %s" % label_file)
                return False
            self.imageData = self.labelFile.imageData
            self.imagePath = os.path.join(os.path.dirname(label_file),
                                          self.labelFile.imagePath)
            self.lineColor = QtGui.QColor(*self.labelFile.lineColor)
            self.fillColor = QtGui.QColor(*self.labelFile.fillColor)
            self.otherData = self.labelFile.otherData
        else:
            # Load image:
            # read data first and store for saving into label file.
            self.imageData = read(filename, None)
            if self.imageData is not None:
                # the filename is image not JSON
                self.imagePath = filename
            self.labelFile = None
        image = QtGui.QImage.fromData(self.imageData)
        if image.isNull():
            formats = ['*.{}'.format(fmt.data().decode())
                       for fmt in QtGui.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.image = image
        self.filename = filename
        self.canvas.loadPixmap(QtGui.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)
        self.status("Loaded %s" % os.path.basename(str(filename)))
        return True