labelFile.py 2.4 KB
Newer Older
M
Michael Pitidis 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#
# Copyright (C) 2011 Michael Pitidis, Hussein Abdulwahid.
#
# This file is part of Labelme.
#
# Labelme is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Labelme is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Labelme.  If not, see <http://www.gnu.org/licenses/>.
#
M
Michael Pitidis 已提交
19 20 21 22 23 24 25 26 27 28 29 30

import json
import os.path

from base64 import b64encode, b64decode

class LabelFileError(Exception):
    pass

class LabelFile(object):
    suffix = '.lif'

31
    def __init__(self, filename=None):
M
Michael Pitidis 已提交
32 33 34
        self.shapes = ()
        self.imagePath = None
        self.imageData = None
35 36
        if filename is not None:
            self.load(filename)
M
Michael Pitidis 已提交
37 38 39 40 41 42 43

    def load(self, filename):
        try:
            with open(filename, 'rb') as f:
                data = json.load(f)
                imagePath = data['imagePath']
                imageData = b64decode(data['imageData'])
44 45 46 47
                lineColor = data['lineColor']
                fillColor = data['fillColor']
                shapes = ((s['label'], s['points'], s['line_color'], s['fill_color'])\
                        for s in data['shapes'])
M
Michael Pitidis 已提交
48 49 50 51
                # Only replace data after everything is loaded.
                self.shapes = shapes
                self.imagePath = imagePath
                self.imageData = imageData
52 53
                self.lineColor = lineColor
                self.fillColor = fillColor
M
Michael Pitidis 已提交
54 55 56
        except Exception, e:
            raise LabelFileError(e)

57 58
    def save(self, filename, shapes, imagePath, imageData,
            lineColor=None, fillColor=None):
M
Michael Pitidis 已提交
59 60 61
        try:
            with open(filename, 'wb') as f:
                json.dump(dict(
62 63
                    shapes=shapes,
                    lineColor=lineColor, fillColor=fillColor,
M
Michael Pitidis 已提交
64 65 66 67 68 69 70 71 72 73
                    imagePath=imagePath,
                    imageData=b64encode(imageData)),
                    f, ensure_ascii=True, indent=2)
        except Exception, e:
            raise LabelFileError(e)

    @staticmethod
    def isLabelFile(filename):
        return os.path.splitext(filename)[1].lower() == LabelFile.suffix