├── MANIFEST.in
├── labelme
├── __init__.py
├── icons
│ ├── eye.png
│ ├── fit.png
│ ├── new.png
│ ├── cancel.png
│ ├── close.png
│ ├── color.png
│ ├── copy.png
│ ├── delete.png
│ ├── done.png
│ ├── edit.png
│ ├── expert.png
│ ├── file.png
│ ├── help.png
│ ├── icon.png
│ ├── labels.png
│ ├── open.png
│ ├── quit.png
│ ├── save.png
│ ├── undo.png
│ ├── zoom.png
│ ├── objects.png
│ ├── save-as.png
│ ├── zoom-in.png
│ ├── zoom-out.png
│ ├── color_line.png
│ ├── fit-width.png
│ ├── fit-window.png
│ ├── undo-cross.png
│ ├── feBlend-icon.png
│ ├── open.svg
│ ├── done.svg
│ └── save.svg
├── resources.qrc
├── zoomWidget.py
├── toolBar.py
├── colorDialog.py
├── labelFile.py
├── lib.py
├── labelDialog.py
├── choiceDialog.py
├── utils.py
├── shape.py
└── canvas.py
├── setup.cfg
├── 使用教程.pdf
├── .gitattributes
├── .readme
├── edit.png
├── main.png
├── next.png
├── open.png
├── delete.png
├── label.png
├── relabel.png
├── repeat.png
├── sidebar.png
├── example1.png
├── example2.png
├── example3.png
├── next_person.png
└── prev_person.png
├── tutorial
├── apc2016_obj3.jpg
├── apc2016_obj3_json
│ ├── img.png
│ ├── label.png
│ ├── label_viz.png
│ ├── label_names.txt
│ └── info.yaml
└── load_label_png.py
├── .gitignore
├── tests
└── test_utils.py
├── scripts
├── labelme_draw_json
├── labelme_json_to_dataset
└── labelme_on_docker
├── docker
└── Dockerfile
├── README.md
├── .travis.yml
├── setup.py
└── LICENSE
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include README.md
2 |
--------------------------------------------------------------------------------
/labelme/__init__.py:
--------------------------------------------------------------------------------
1 | from labelme import utils
2 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [flake8]
2 | exclude = .anaconda2/*,labelme/*
3 |
--------------------------------------------------------------------------------
/使用教程.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/使用教程.pdf
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/.readme/edit.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/.readme/edit.png
--------------------------------------------------------------------------------
/.readme/main.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/.readme/main.png
--------------------------------------------------------------------------------
/.readme/next.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/.readme/next.png
--------------------------------------------------------------------------------
/.readme/open.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/.readme/open.png
--------------------------------------------------------------------------------
/.readme/delete.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/.readme/delete.png
--------------------------------------------------------------------------------
/.readme/label.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/.readme/label.png
--------------------------------------------------------------------------------
/.readme/relabel.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/.readme/relabel.png
--------------------------------------------------------------------------------
/.readme/repeat.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/.readme/repeat.png
--------------------------------------------------------------------------------
/.readme/sidebar.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/.readme/sidebar.png
--------------------------------------------------------------------------------
/.readme/example1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/.readme/example1.png
--------------------------------------------------------------------------------
/.readme/example2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/.readme/example2.png
--------------------------------------------------------------------------------
/.readme/example3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/.readme/example3.png
--------------------------------------------------------------------------------
/labelme/icons/eye.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/eye.png
--------------------------------------------------------------------------------
/labelme/icons/fit.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/fit.png
--------------------------------------------------------------------------------
/labelme/icons/new.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/new.png
--------------------------------------------------------------------------------
/.readme/next_person.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/.readme/next_person.png
--------------------------------------------------------------------------------
/.readme/prev_person.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/.readme/prev_person.png
--------------------------------------------------------------------------------
/labelme/icons/cancel.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/cancel.png
--------------------------------------------------------------------------------
/labelme/icons/close.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/close.png
--------------------------------------------------------------------------------
/labelme/icons/color.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/color.png
--------------------------------------------------------------------------------
/labelme/icons/copy.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/copy.png
--------------------------------------------------------------------------------
/labelme/icons/delete.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/delete.png
--------------------------------------------------------------------------------
/labelme/icons/done.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/done.png
--------------------------------------------------------------------------------
/labelme/icons/edit.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/edit.png
--------------------------------------------------------------------------------
/labelme/icons/expert.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/expert.png
--------------------------------------------------------------------------------
/labelme/icons/file.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/file.png
--------------------------------------------------------------------------------
/labelme/icons/help.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/help.png
--------------------------------------------------------------------------------
/labelme/icons/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/icon.png
--------------------------------------------------------------------------------
/labelme/icons/labels.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/labels.png
--------------------------------------------------------------------------------
/labelme/icons/open.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/open.png
--------------------------------------------------------------------------------
/labelme/icons/quit.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/quit.png
--------------------------------------------------------------------------------
/labelme/icons/save.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/save.png
--------------------------------------------------------------------------------
/labelme/icons/undo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/undo.png
--------------------------------------------------------------------------------
/labelme/icons/zoom.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/zoom.png
--------------------------------------------------------------------------------
/labelme/icons/objects.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/objects.png
--------------------------------------------------------------------------------
/labelme/icons/save-as.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/save-as.png
--------------------------------------------------------------------------------
/labelme/icons/zoom-in.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/zoom-in.png
--------------------------------------------------------------------------------
/labelme/icons/zoom-out.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/zoom-out.png
--------------------------------------------------------------------------------
/tutorial/apc2016_obj3.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/tutorial/apc2016_obj3.jpg
--------------------------------------------------------------------------------
/labelme/icons/color_line.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/color_line.png
--------------------------------------------------------------------------------
/labelme/icons/fit-width.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/fit-width.png
--------------------------------------------------------------------------------
/labelme/icons/fit-window.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/fit-window.png
--------------------------------------------------------------------------------
/labelme/icons/undo-cross.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/undo-cross.png
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .cache/
2 | build/
3 | dist/
4 | *.py[cdo]
5 | *.egg-info/
6 |
7 | icons/.DS_Store
8 | labelme/resources.py
9 |
--------------------------------------------------------------------------------
/labelme/icons/feBlend-icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/labelme/icons/feBlend-icon.png
--------------------------------------------------------------------------------
/tutorial/apc2016_obj3_json/img.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/tutorial/apc2016_obj3_json/img.png
--------------------------------------------------------------------------------
/tutorial/apc2016_obj3_json/label.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/tutorial/apc2016_obj3_json/label.png
--------------------------------------------------------------------------------
/tutorial/apc2016_obj3_json/label_viz.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jeffffffli/labelKeypoint/HEAD/tutorial/apc2016_obj3_json/label_viz.png
--------------------------------------------------------------------------------
/tutorial/apc2016_obj3_json/label_names.txt:
--------------------------------------------------------------------------------
1 | background
2 | highland_6539_self_stick_notes
3 | mead_index_cards
4 | kong_air_dog_squeakair_tennis_ball
5 |
--------------------------------------------------------------------------------
/tutorial/apc2016_obj3_json/info.yaml:
--------------------------------------------------------------------------------
1 | label_names:
2 | - background
3 | - highland_6539_self_stick_notes
4 | - mead_index_cards
5 | - kong_air_dog_squeakair_tennis_ball
6 |
--------------------------------------------------------------------------------
/tests/test_utils.py:
--------------------------------------------------------------------------------
1 | import json
2 | import os.path as osp
3 |
4 | import numpy as np
5 |
6 | from labelme import utils
7 |
8 |
9 | here = osp.dirname(osp.abspath(__file__))
10 |
11 |
12 | def test_img_b64_to_array():
13 | json_file = osp.join(here, '../tutorial/apc2016_obj3.json')
14 | data = json.load(open(json_file))
15 | img_b64 = data['imageData']
16 | img = utils.img_b64_to_array(img_b64)
17 | assert img.dtype == np.uint8
18 | assert img.shape == (907, 1210, 3)
19 |
--------------------------------------------------------------------------------
/scripts/labelme_draw_json:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import argparse
4 | import json
5 | import matplotlib.pyplot as plt
6 |
7 | from labelme import utils
8 |
9 |
10 | def main():
11 | parser = argparse.ArgumentParser()
12 | parser.add_argument('json_file')
13 | args = parser.parse_args()
14 |
15 | json_file = args.json_file
16 |
17 | data = json.load(open(json_file))
18 |
19 | img = utils.img_b64_to_array(data['imageData'])
20 | lbl, lbl_names = utils.labelme_shapes_to_label(img.shape, data['shapes'])
21 |
22 | captions = ['%d: %s' % (l, name) for l, name in enumerate(lbl_names)]
23 | lbl_viz = utils.draw_label(lbl, img, captions)
24 |
25 | plt.subplot(121)
26 | plt.imshow(img)
27 | plt.subplot(122)
28 | plt.imshow(lbl_viz)
29 | plt.show()
30 |
31 |
32 | if __name__ == '__main__':
33 | main()
34 |
--------------------------------------------------------------------------------
/tutorial/load_label_png.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | from __future__ import print_function
4 |
5 | import os.path as osp
6 |
7 | import numpy as np
8 | import PIL.Image
9 |
10 |
11 | here = osp.dirname(osp.abspath(__file__))
12 |
13 |
14 | def main():
15 | label_png = osp.join(here, 'apc2016_obj3_json/label.png')
16 | print('Loading:', label_png)
17 | print()
18 |
19 | lbl = np.asarray(PIL.Image.open(label_png))
20 | labels = np.unique(lbl)
21 |
22 | label_names_txt = osp.join(here, 'apc2016_obj3_json/label_names.txt')
23 | label_names = [name.strip() for name in open(label_names_txt)]
24 | print('# of labels:', len(labels))
25 | print('# of label_names:', len(label_names))
26 | if len(labels) != len(label_names):
27 | print('Number of unique labels and label_names must be same.')
28 | quit(1)
29 | print()
30 |
31 | print('label: label_name')
32 | for label, label_name in zip(labels, label_names):
33 | print('%d: %s' % (label, label_name))
34 |
35 |
36 | if __name__ == '__main__':
37 | main()
38 |
--------------------------------------------------------------------------------
/docker/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM ubuntu:trusty
2 |
3 | # http://fabiorehm.com/blog/2014/09/11/running-gui-apps-with-docker/
4 | RUN export uid=1000 gid=1000 && \
5 | mkdir -p /home/developer && \
6 | echo "developer:x:${uid}:${gid}:Developer,,,:/home/developer:/bin/bash" >> /etc/passwd && \
7 | echo "developer:x:${uid}:" >> /etc/group && \
8 | echo "developer ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/developer && \
9 | chmod 0440 /etc/sudoers.d/developer && \
10 | chown ${uid}:${gid} -R /home/developer
11 |
12 | RUN \
13 | apt-get update -qq && \
14 | apt-get upgrade -qq -y && \
15 | apt-get install -qq -y \
16 | aptitude \
17 | git \
18 | python \
19 | python-setuptools
20 |
21 | RUN \
22 | easy_install -q pip && \
23 | pip install -q -U pip setuptools
24 |
25 | RUN apt-get install -qq -y python-qt4 pyqt4-dev-tools
26 | RUN apt-get install -qq -y python-matplotlib
27 | RUN apt-get install -qq -y python-scipy
28 | RUN apt-get install -qq -y python-skimage
29 |
30 | RUN pip install -v git+https://github.com/wkentaro/labelme.git
31 |
32 | USER developer
33 | ENV HOME /home/developer
34 |
--------------------------------------------------------------------------------
/labelme/resources.qrc:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | icons/help.png
5 | icons/icon.png
6 | icons/expert.png
7 | icons/done.png
8 | icons/file.png
9 | icons/labels.png
10 | icons/objects.png
11 | icons/close.png
12 | icons/fit-width.png
13 | icons/fit-window.png
14 | icons/undo.png
15 | icons/eye.png
16 | icons/quit.png
17 | icons/copy.png
18 | icons/edit.png
19 | icons/open.png
20 | icons/save.png
21 | icons/save-as.png
22 | icons/color.png
23 | icons/color_line.png
24 | icons/zoom.png
25 | icons/zoom-in.png
26 | icons/zoom-out.png
27 | icons/cancel.png
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/labelme/zoomWidget.py:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (C) 2011 Michael Pitidis, Hussein Abdulwahid.
3 | #
4 | # This file is part of Labelme.
5 | #
6 | # Labelme is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # Labelme is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with Labelme. If not, see .
18 | #
19 |
20 | try:
21 | from PyQt5.QtGui import *
22 | from PyQt5.QtCore import *
23 | from PyQt5.QtWidgets import *
24 | except ImportError:
25 | from PyQt4.QtGui import *
26 | from PyQt4.QtCore import *
27 |
28 |
29 | class ZoomWidget(QSpinBox):
30 | def __init__(self, value=100):
31 | super(ZoomWidget, self).__init__()
32 | self.setButtonSymbols(QAbstractSpinBox.NoButtons)
33 | self.setRange(1, 500)
34 | self.setSuffix(' %')
35 | self.setValue(value)
36 | self.setToolTip('Zoom Level')
37 | self.setStatusTip(self.toolTip())
38 | self.setAlignment(Qt.AlignCenter)
39 |
40 | def minimumSizeHint(self):
41 | height = super(ZoomWidget, self).minimumSizeHint().height()
42 | fm = QFontMetrics(self.font())
43 | width = fm.width(str(self.maximum()))
44 | return QSize(width, height)
45 |
46 |
--------------------------------------------------------------------------------
/scripts/labelme_json_to_dataset:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import argparse
4 | import json
5 | import os
6 | import os.path as osp
7 | import warnings
8 |
9 | import numpy as np
10 | import PIL.Image
11 | import yaml
12 |
13 | from labelme import utils
14 |
15 |
16 | def main():
17 | parser = argparse.ArgumentParser()
18 | parser.add_argument('json_file')
19 | parser.add_argument('-o', '--out', default=None)
20 | args = parser.parse_args()
21 |
22 | json_file = args.json_file
23 |
24 | if args.out is None:
25 | out_dir = osp.basename(json_file).replace('.', '_')
26 | out_dir = osp.join(osp.dirname(json_file), out_dir)
27 | else:
28 | out_dir = args.out
29 | if not osp.exists(out_dir):
30 | os.mkdir(out_dir)
31 |
32 | data = json.load(open(json_file))
33 |
34 | img = utils.img_b64_to_array(data['imageData'])
35 | lbl, lbl_names = utils.labelme_shapes_to_label(img.shape, data['shapes'])
36 |
37 | captions = ['%d: %s' % (l, name) for l, name in enumerate(lbl_names)]
38 | lbl_viz = utils.draw_label(lbl, img, captions)
39 |
40 | PIL.Image.fromarray(img).save(osp.join(out_dir, 'img.png'))
41 | PIL.Image.fromarray(lbl).save(osp.join(out_dir, 'label.png'))
42 | PIL.Image.fromarray(lbl_viz).save(osp.join(out_dir, 'label_viz.png'))
43 |
44 | with open(osp.join(out_dir, 'label_names.txt'), 'w') as f:
45 | for lbl_name in lbl_names:
46 | f.write(lbl_name + '\n')
47 |
48 | warnings.warn('info.yaml is being replaced by label_names.txt')
49 | info = dict(label_names=lbl_names)
50 | with open(osp.join(out_dir, 'info.yaml'), 'w') as f:
51 | yaml.safe_dump(info, f, default_flow_style=False)
52 |
53 | print('Saved to: %s' % out_dir)
54 |
55 |
56 | if __name__ == '__main__':
57 | main()
58 |
--------------------------------------------------------------------------------
/labelme/toolBar.py:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (C) 2011 Michael Pitidis, Hussein Abdulwahid.
3 | #
4 | # This file is part of Labelme.
5 | #
6 | # Labelme is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # Labelme is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with Labelme. If not, see .
18 | #
19 |
20 | try:
21 | from PyQt5.QtGui import *
22 | from PyQt5.QtCore import *
23 | from PyQt5.QtWidgets import *
24 | except ImportError:
25 | from PyQt4.QtGui import *
26 | from PyQt4.QtCore import *
27 |
28 |
29 | class ToolBar(QToolBar):
30 | def __init__(self, title):
31 | super(ToolBar, self).__init__(title)
32 | layout = self.layout()
33 | m = (0, 0, 0, 0)
34 | layout.setSpacing(0)
35 | layout.setContentsMargins(*m)
36 | self.setContentsMargins(*m)
37 | self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint)
38 |
39 | def addAction(self, action):
40 | if isinstance(action, QWidgetAction):
41 | return super(ToolBar, self).addAction(action)
42 | btn = ToolButton()
43 | btn.setDefaultAction(action)
44 | btn.setToolButtonStyle(self.toolButtonStyle())
45 | self.addWidget(btn)
46 |
47 |
48 | class ToolButton(QToolButton):
49 | """ToolBar companion class which ensures all buttons have the same size."""
50 | minSize = (60, 60)
51 | def minimumSizeHint(self):
52 | ms = super(ToolButton, self).minimumSizeHint()
53 | w1, h1 = ms.width(), ms.height()
54 | w2, h2 = self.minSize
55 | ToolButton.minSize = max(w1, w2), max(h1, h2)
56 | return QSize(*ToolButton.minSize)
57 |
58 |
--------------------------------------------------------------------------------
/labelme/colorDialog.py:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (C) 2011 Michael Pitidis, Hussein Abdulwahid.
3 | #
4 | # This file is part of Labelme.
5 | #
6 | # Labelme is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # Labelme is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with Labelme. If not, see .
18 | #
19 |
20 | try:
21 | from PyQt5.QtGui import *
22 | from PyQt5.QtCore import *
23 | from PyQt5.QtWidgets import *
24 | except ImportError:
25 | from PyQt4.QtGui import *
26 | from PyQt4.QtCore import *
27 |
28 |
29 | BB = QDialogButtonBox
30 |
31 | class ColorDialog(QColorDialog):
32 | def __init__(self, parent=None):
33 | super(ColorDialog, self).__init__(parent)
34 | self.setOption(QColorDialog.ShowAlphaChannel)
35 | # The Mac native dialog does not support our restore button.
36 | self.setOption(QColorDialog.DontUseNativeDialog)
37 | ## Add a restore defaults button.
38 | # The default is set at invocation time, so that it
39 | # works across dialogs for different elements.
40 | self.default = None
41 | self.bb = self.layout().itemAt(1).widget()
42 | self.bb.addButton(BB.RestoreDefaults)
43 | self.bb.clicked.connect(self.checkRestore)
44 |
45 | def getColor(self, value=None, title=None, default=None):
46 | self.default = default
47 | if title:
48 | self.setWindowTitle(title)
49 | if value:
50 | self.setCurrentColor(value)
51 | return self.currentColor() if self.exec_() else None
52 |
53 | def checkRestore(self, button):
54 | if self.bb.buttonRole(button) & BB.ResetRole and self.default:
55 | self.setCurrentColor(self.default)
56 |
57 |
--------------------------------------------------------------------------------
/scripts/labelme_on_docker:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import argparse
4 | import json
5 | import os
6 | import os.path as osp
7 | import platform
8 | import shlex
9 | import subprocess
10 | import sys
11 |
12 |
13 | def get_ip():
14 | dist = platform.platform().split('-')[0]
15 | if dist == 'Linux':
16 | return ''
17 | elif dist == 'Darwin':
18 | cmd = 'ifconfig en0'
19 | output = subprocess.check_output(shlex.split(cmd))
20 | for row in output.splitlines():
21 | cols = row.strip().split(' ')
22 | if cols[0] == 'inet':
23 | ip = cols[1]
24 | return ip
25 | else:
26 | raise RuntimeError('No ip is found.')
27 | else:
28 | raise RuntimeError('Unsupported platform.')
29 |
30 |
31 | def labelme_on_docker(image_file, out_file):
32 | ip = get_ip()
33 | cmd = 'xhost + %s' % ip
34 | subprocess.check_output(shlex.split(cmd))
35 |
36 | out_file = osp.abspath(out_file)
37 | if osp.exists(out_file):
38 | raise RuntimeError('File exists: %s' % out_file)
39 | else:
40 | open(osp.abspath(out_file), 'w')
41 |
42 | cmd = 'docker run -it --rm' \
43 | ' -e DISPLAY={0}:0' \
44 | ' -e QT_X11_NO_MITSHM=1' \
45 | ' -v /tmp/.X11-unix:/tmp/.X11-unix' \
46 | ' -v {1}:{2}' \
47 | ' -v {3}:{4}' \
48 | ' -w /home/developer' \
49 | ' labelme' \
50 | ' labelme {2} -O {4}'
51 | cmd = cmd.format(
52 | ip,
53 | osp.abspath(image_file),
54 | osp.join('/home/developer', osp.basename(image_file)),
55 | osp.abspath(out_file),
56 | osp.join('/home/developer', osp.basename(out_file)),
57 | )
58 | subprocess.call(shlex.split(cmd))
59 |
60 | try:
61 | json.load(open(out_file))
62 | return out_file
63 | except Exception as e:
64 | if open(out_file).read() == '':
65 | os.remove(out_file)
66 | raise RuntimeError('Annotation is cancelled.')
67 |
68 |
69 | def main():
70 | parser = argparse.ArgumentParser()
71 | parser.add_argument('image_file')
72 | parser.add_argument('-O', '--output', required=True)
73 | args = parser.parse_args()
74 |
75 | try:
76 | out_file = labelme_on_docker(args.image_file, args.output)
77 | print('Saved to: %s' % out_file)
78 | except RuntimeError as e:
79 | sys.stderr.write(e.__str__() + '\n')
80 | sys.exit(1)
81 |
82 |
83 | if __name__ == '__main__':
84 | main()
85 |
--------------------------------------------------------------------------------
/labelme/labelFile.py:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (C) 2011 Michael Pitidis, Hussein Abdulwahid.
3 | #
4 | # This file is part of Labelme.
5 | #
6 | # Labelme is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # Labelme is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with Labelme. If not, see .
18 | #
19 |
20 | from base64 import b64encode, b64decode
21 | import json
22 | import os.path
23 | import sys
24 |
25 |
26 | PY2 = sys.version_info[0] == 2
27 |
28 |
29 | class LabelFileError(Exception):
30 | pass
31 |
32 | class LabelFile(object):
33 | suffix = '.json'
34 |
35 | def __init__(self, filename=None):
36 | self.shapes = ()
37 | self.imagePath = None
38 | self.imageData = None
39 | if filename is not None:
40 | self.load(filename)
41 |
42 | def load(self, filename):
43 | try:
44 | with open(filename, 'rb' if PY2 else 'r') as f:
45 | data = json.load(f)
46 | imagePath = data['imagePath']
47 | imageData = b64decode(data['imageData'])
48 | lineColor = data['lineColor']
49 | fillColor = data['fillColor']
50 | shapes = ((s['label'], s['points'], s['line_color'], s['fill_color'])\
51 | for s in data['shapes'])
52 | # Only replace data after everything is loaded.
53 | self.shapes = shapes
54 | self.imagePath = imagePath
55 | self.imageData = imageData
56 | self.lineColor = lineColor
57 | self.fillColor = fillColor
58 | except Exception as e:
59 | raise LabelFileError(e)
60 |
61 | def save(self, filename, shapes, imagePath, imageData,
62 | lineColor=None, fillColor=None):
63 | data = dict(
64 | shapes=shapes,
65 | imagePath=imagePath,
66 | )
67 | try:
68 | with open(filename, 'wb' if PY2 else 'w') as f:
69 | json.dump(data, f, ensure_ascii=True, indent=2)
70 | except Exception as e:
71 | raise LabelFileError(e)
72 |
73 | @staticmethod
74 | def isLabelFile(filename):
75 | return os.path.splitext(filename)[1].lower() == LabelFile.suffix
76 |
--------------------------------------------------------------------------------
/labelme/lib.py:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (C) 2011 Michael Pitidis, Hussein Abdulwahid.
3 | #
4 | # This file is part of Labelme.
5 | #
6 | # Labelme is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # Labelme is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with Labelme. If not, see .
18 | #
19 |
20 | from math import sqrt
21 |
22 | try:
23 | from PyQt5.QtGui import *
24 | from PyQt5.QtCore import *
25 | from PyQt5.QtWidgets import *
26 | except ImportError:
27 | from PyQt4.QtGui import *
28 | from PyQt4.QtCore import *
29 |
30 |
31 | def newIcon(icon):
32 | return QIcon(':/' + icon)
33 |
34 | def newButton(text, icon=None, slot=None):
35 | b = QPushButton(text)
36 | if icon is not None:
37 | b.setIcon(newIcon(icon))
38 | if slot is not None:
39 | b.clicked.connect(slot)
40 | return b
41 |
42 | def newAction(parent, text, slot=None, shortcut=None, icon=None,
43 | tip=None, checkable=False, enabled=True):
44 | """Create a new action and assign callbacks, shortcuts, etc."""
45 | a = QAction(text, parent)
46 | if icon is not None:
47 | a.setIcon(newIcon(icon))
48 | if shortcut is not None:
49 | if isinstance(shortcut, (list, tuple)):
50 | a.setShortcuts(shortcut)
51 | else:
52 | a.setShortcut(shortcut)
53 | if tip is not None:
54 | a.setToolTip(tip)
55 | a.setStatusTip(tip)
56 | if slot is not None:
57 | a.triggered.connect(slot)
58 | if checkable:
59 | a.setCheckable(True)
60 | a.setEnabled(enabled)
61 | return a
62 |
63 |
64 | def addActions(widget, actions):
65 | for action in actions:
66 | if action is None:
67 | widget.addSeparator()
68 | elif isinstance(action, QMenu):
69 | widget.addMenu(action)
70 | else:
71 | widget.addAction(action)
72 |
73 | def labelValidator():
74 | return QRegExpValidator(QRegExp(r'^[^ \t].+'), None)
75 |
76 |
77 | class struct(object):
78 | def __init__(self, **kwargs):
79 | self.__dict__.update(kwargs)
80 |
81 | def distance(p):
82 | return sqrt(p.x() * p.x() + p.y() * p.y())
83 |
84 | def fmtShortcut(text):
85 | mod, key = text.split('+', 1)
86 | return '%s+%s' % (mod, key)
87 |
88 |
--------------------------------------------------------------------------------
/labelme/labelDialog.py:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (C) 2011 Michael Pitidis, Hussein Abdulwahid.
3 | #
4 | # This file is part of Labelme.
5 | #
6 | # Labelme is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # Labelme is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with Labelme. If not, see .
18 | #
19 | from copy import deepcopy
20 | try:
21 | from PyQt5.QtGui import *
22 | from PyQt5.QtCore import *
23 | from PyQt5.QtWidgets import *
24 | PYQT5 = True
25 | except ImportError:
26 | from PyQt4.QtGui import *
27 | from PyQt4.QtCore import *
28 | PYQT5 = False
29 |
30 | from .lib import newIcon, labelValidator
31 |
32 | # TODO:
33 | # - Calculate optimal position so as not to go out of screen area.
34 |
35 | BB = QDialogButtonBox
36 |
37 | class LabelDialog(QDialog):
38 |
39 | def __init__(self, text="Enter object label", parent=None):
40 | super(LabelDialog, self).__init__(parent)
41 | self.edit = QLineEdit()
42 | self.edit.setText(text)
43 | self.edit.setValidator(labelValidator())
44 | self.edit.editingFinished.connect(self.postProcess)
45 | layout = QVBoxLayout()
46 | layout.addWidget(self.edit)
47 | self.buttonBox = bb = BB(BB.Ok | BB.Cancel, Qt.Horizontal, self)
48 | bb.button(BB.Ok).setIcon(newIcon('done'))
49 | bb.button(BB.Cancel).setIcon(newIcon('undo'))
50 | bb.accepted.connect(self.validate)
51 | bb.rejected.connect(self.reject)
52 | layout.addWidget(bb)
53 | self.setLayout(layout)
54 |
55 | def validate(self):
56 | if PYQT5:
57 | if self.edit.text().strip():
58 | self.accept()
59 | else:
60 | if self.edit.text().trimmed():
61 | self.accept()
62 |
63 | def postProcess(self):
64 | if PYQT5:
65 | self.edit.setText(self.edit.text().strip())
66 | else:
67 | self.edit.setText(self.edit.text().trimmed())
68 |
69 | def popUp(self, text='', move=True, notice=False):
70 | self.edit.setText(text)
71 | self.edit.setSelection(0, len(text))
72 | self.edit.setFocus(Qt.PopupFocusReason)
73 | if notice:
74 | self.edit.setText(text)
75 | if move:
76 | self.move(QCursor.pos())
77 | return self.edit.text() if self.exec_() else None
78 |
79 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | labelme: Image Annotation Tool with Python
2 | ==========================================
3 |
4 | [](https://pypi.python.org/pypi/labelme)
5 | [](https://travis-ci.org/wkentaro/labelme)
6 | [](https://hub.docker.com/r/wkentaro/labelme)
7 |
8 | Requirements
9 | ------------
10 |
11 | - Ubuntu / macOS / Windows
12 | - Python2 / Python3
13 | - [PyQt4 / PyQt5](http://www.riverbankcomputing.co.uk/software/pyqt/intro)
14 |
15 |
16 | Installation
17 | ------------
18 |
19 | **Anaconda**
20 |
21 | You need install [Anaconda](https://www.continuum.io/downloads), then run below:
22 |
23 | For linux and Mac
24 |
25 | ```bash
26 | # python2
27 | cd $root_dir_of_labelme
28 | conda create --name=labelme python=2.7
29 | source activate labelme
30 | conda install pyqt
31 | pip install labelme
32 | ```
33 |
34 | For windows
35 | ```bash
36 | # python2
37 | cd $root_dir_of_labelme
38 | conda create --name=labelme python=2.7
39 | activate labelme
40 | conda install pyqt
41 | pip install labelme
42 | ```
43 |
44 | Usage
45 | -----
46 |
47 | **准备**
48 |
49 | 下载[`coco_anno`](https://drive.google.com/open?id=1_1_E9dr-X33HpmU5Ffo60NCOyrS-ATSB)文件夹,把文件夹路径复制到`labelKeypoint/labelme/app.py`的第100行。比如,我的路径是`/mnt/c/Users/ljf_l/Desktop/coco_anno`,则修改如下
50 | ``` python
51 | self.datadir = '/mnt/c/Users/ljf_l/Desktop/coco_anno'
52 | ```
53 |
54 | **Install**
55 | ```bash
56 | # Install
57 | $ pip uninstall labelme
58 | $ python setup.py install
59 | ```
60 |
61 | **运行**
62 |
63 | ```bash
64 | # Run
65 | $ labelme # Open GUI
66 | ```
67 |
68 | **标注**
69 |
70 | 打开软件之后,选择右侧的open,开始标记
71 |
72 |
73 |
74 | 标注的主界面如下
75 |
76 |
77 |
78 | 左上方第一个数字表示当前标注的图片序号,`person:`表示当前标记的人的序号,`progress:`表示当前图片已经标记好的人的数量。
79 |
80 | 点击鼠标左键即可开始标记。
81 |
82 |
83 |
84 | 选择`Head`表示标注头部,`Neck`标注脖子。对于没办法预测的部位,可以不标注。如果头和脖子都没有,请在框内任意点击一个位置,选择`Empty`,表示当前人的头和脖子均难以预测,无法标记。
85 |
86 | 如果对一个人的相同部位重复标记,会弹出提示窗口,关闭即可。
87 |
88 |
89 |
90 | 选择`next person`或`prev person`可以切换到不同的人进行标记。
91 |
92 |
93 |
94 |
95 | 如果标记错误,可选择`Edit`后,在右侧选择相应的部位,进行删除
96 |
97 |
98 |
99 |
100 |
101 |
102 | 然后点击`Create`重新进入标注状态
103 |
104 |
105 |
106 | 当所有人都标记完后,选择`next`标注下一张图。此时程序会自动保存已经标记好的图片。
107 |
108 |
109 |
110 | 中途如果程序关闭,进度会自动保存,下次点击`open`会从直接上次未标注完成的图片出打开,继续标注。
111 |
112 | **标注例子**
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 | Acknowledgement
123 | ---------------
124 |
125 | This repo is the fork of [mpitid/pylabelme](https://github.com/mpitid/pylabelme),
126 | whose development has already stopped.
127 |
--------------------------------------------------------------------------------
/labelme/choiceDialog.py:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (C) 2011 Michael Pitidis, Hussein Abdulwahid.
3 | #
4 | # This file is part of Labelme.
5 | #
6 | # Labelme is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # Labelme is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with Labelme. If not, see .
18 | #
19 |
20 | try:
21 | from PyQt5.QtGui import *
22 | from PyQt5.QtCore import *
23 | from PyQt5.QtWidgets import *
24 | PYQT5 = True
25 | except ImportError:
26 | from PyQt4.QtGui import *
27 | from PyQt4.QtCore import *
28 | PYQT5 = False
29 |
30 | from .lib import newIcon, labelValidator
31 |
32 | # TODO:
33 | # - Calculate optimal position so as not to go out of screen area.
34 |
35 | BB = QDialogButtonBox
36 | #BB = QRadioButton
37 |
38 | class ChoiceDialog(QDialog):
39 |
40 | def __init__(self, text="Choose object label", parent=None):
41 | super(ChoiceDialog, self).__init__(parent)
42 | self.edit = QLineEdit()
43 | self.edit.setText(text)
44 | self.edit.setEnabled(False)
45 | self.edit.setValidator(labelValidator())
46 | self.edit.editingFinished.connect(self.postProcess)
47 | layout = QVBoxLayout()
48 | layout.addWidget(self.edit)
49 | self.buttonBox = bb = BB(BB.Save | BB.Ok | BB.Cancel | BB.Discard , Qt.Horizontal, self)
50 | #bb.button(BB.Ok).setIcon(newIcon('done'))
51 | #bb.button(BB.Cancel).setIcon(newIcon('undo'))
52 | bb.button(BB.Ok).setText('Head')
53 | bb.button(BB.Discard).setText('Empty')
54 | bb.button(BB.Save).setText('Neck')
55 | bb.button(BB.Cancel).setIcon(newIcon('undo'))
56 |
57 | bb.button(BB.Ok).clicked.connect(self.head)
58 | bb.button(BB.Discard).clicked.connect(self.empty)
59 | bb.button(BB.Save).clicked.connect(self.neck)
60 |
61 | bb.accepted.connect(self.validate)
62 | bb.rejected.connect(self.reject)
63 | layout.addWidget(bb)
64 | self.setLayout(layout)
65 |
66 | def head(self):
67 | self.edit.setText('Head')
68 | self.accept()
69 |
70 | def empty(self):
71 | self.edit.setText('Empty')
72 | self.accept()
73 |
74 | def neck(self):
75 | self.edit.setText('Neck')
76 | self.accept()
77 |
78 | def validate(self):
79 | if PYQT5:
80 | if self.edit.text().strip():
81 | self.accept()
82 | else:
83 | if self.edit.text().trimmed():
84 | self.accept()
85 |
86 | def postProcess(self):
87 | if PYQT5:
88 | self.edit.setText(self.edit.text().strip())
89 | else:
90 | self.edit.setText(self.edit.text().trimmed())
91 |
92 | def popUp(self, text='', move=True):
93 | self.edit.setText(text)
94 | self.edit.setSelection(0, len(text))
95 | self.edit.setFocus(Qt.PopupFocusReason)
96 | if move:
97 | self.move(QCursor.pos())
98 | return self.edit.text() if self.exec_() else None
99 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | sudo: false
2 |
3 | cache: pip
4 |
5 | matrix:
6 | include:
7 | - os: linux
8 | dist: trusty
9 | language: python
10 | env:
11 | - SYSTEM_PYTHON=/usr/bin/python
12 | - PIP=pip
13 | - PYTHON=python
14 | addons:
15 | apt:
16 | packages:
17 | - gfortran
18 | - liblapack-dev
19 | - pyqt4-dev-tools
20 | - python-qt4
21 | # FIXME: brew cannot be run on Travis.
22 | # - os: osx
23 | # osx_image: xcode8
24 | # language: generic
25 | # env:
26 | # - PYTHON_VERSION=2.7.10
27 | # - PYENV_ROOT=~/.pyenv
28 | # - PATH=$PYENV_ROOT/shims:$PATH:$PYENV_ROOT/bin
29 | # - os: osx
30 | # osx_image: xcode9
31 | # language: generic
32 | # env:
33 | # - PYTHON_VERSION=2.7.10
34 | # - PYENV_ROOT=~/.pyenv
35 | # - PATH=$PYENV_ROOT/shims:$PATH:$PYENV_ROOT/bin
36 | - os: linux
37 | dist: trusty
38 | language: python
39 | python: 2.7
40 | env:
41 | - USE_CONDA=true
42 | - os: linux
43 | dist: trusty
44 | language: python
45 | python: 3.5
46 | env:
47 | - USE_CONDA=true
48 |
49 | before_install:
50 | - if [ "$USE_CONDA" = "true" ]; then
51 | if [ "$TRAVIS_PYTHON_VERSION" = "2.7" ]; then
52 | wget https://repo.continuum.io/miniconda/Miniconda2-latest-Linux-x86_64.sh -O miniconda.sh;
53 | else
54 | wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh -O miniconda.sh;
55 | fi;
56 | bash miniconda.sh -b -p $HOME/miniconda;
57 | export PATH="$HOME/miniconda/bin:$PATH";
58 | hash -r;
59 | conda config --set always_yes yes --set changeps1 no;
60 | conda update -q conda;
61 | conda info -a;
62 | elif [ "$TRAVIS_OS_NAME" = "osx" ]; then
63 | which pyenv &>/dev/null || brew install --quiet pyenv;
64 | PYTHON_CONFIGURE_OPTS="--enable-unicode=ucs2" pyenv install -ks $PYTHON_VERSION;
65 | mkdir -p ~/.matplotlib;
66 | echo backend':' Agg > ~/.matplotlib/matplotlibrc;
67 | fi
68 |
69 | install:
70 | - if [ "$TRAVIS_OS_NAME" = "linux" ]; then
71 | if [ "$USE_CONDA" = "true" ]; then
72 | conda create --name=labelme python=$TRAVIS_PYTHON_VERSION -q -y;
73 | conda install pyqt=4 -q -y;
74 | conda install scikit-image -q -y;
75 | else
76 | cp -r $(dirname $($SYSTEM_PYTHON -c 'import PyQt4; print(PyQt4.__file__)')) ~/virtualenv/python2.7/lib/python2.7/site-packages/;
77 | cp $($SYSTEM_PYTHON -c 'import sip; print(sip.__file__)') ~/virtualenv/python2.7/lib/python2.7/site-packages/;
78 | pip install -q -U pip setuptools;
79 | pip install -q -U numpy scipy scikit-image;
80 | fi;
81 | elif [ "$TRAVIS_OS_NAME" = "osx" ]; then
82 | pyenv global $PYTHON_VERSION;
83 | brew install pyqt;
84 | cp -r /usr/local/lib/python2.7/site-packages/PyQt5 ~/.pyenv/versions/2.7.10/lib/python2.7/site-packages/;
85 | cp /usr/local/lib/python2.7/site-packages/sip.so ~/.pyenv/versions/2.7.10/lib/python2.7/site-packages/;
86 | pip install -q -U pip setuptools;
87 | pip install -q -U numpy scipy scikit-image;
88 | fi
89 | - pip install .
90 |
91 | before_script:
92 | - pip install -q pytest
93 |
94 | script:
95 | - pytest -v tests
96 |
97 | branches:
98 | only:
99 | - master
100 |
101 | notifications:
102 | email: false
103 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from distutils.spawn import find_executable
2 | import os.path as osp
3 | from setuptools.command.develop import develop as DevelopCommand
4 | from setuptools.command.install import install as InstallCommand
5 | from setuptools import find_packages
6 | from setuptools import setup
7 | import shlex
8 | import subprocess
9 | import sys
10 |
11 |
12 | PY3 = sys.version_info[0] == 3
13 | PY2 = sys.version_info[0] == 2
14 |
15 |
16 | version = '2.7.0'
17 |
18 |
19 | install_requires = [
20 | 'matplotlib',
21 | 'numpy',
22 | 'Pillow>=2.8.0',
23 | 'PyYAML',
24 | ]
25 |
26 |
27 | try:
28 | import PyQt5 # NOQA
29 | PYQT_VERSION = 5
30 | except ImportError:
31 | try:
32 | import PyQt4 # NOQA
33 | PYQT_VERSION = 4
34 | except ImportError:
35 | if PY2:
36 | sys.stderr.write(
37 | 'Please install PyQt4 or PyQt5 for Python2.\n'
38 | 'Note that PyQt5 can be installed via pip for Python3.')
39 | sys.exit(1)
40 | assert PY3
41 | # PyQt5 can be installed via pip for Python3
42 | install_requires.append('pyqt5')
43 |
44 |
45 | if sys.argv[1] == 'release':
46 | commands = [
47 | 'git tag v{:s}'.format(version),
48 | 'git push origin master --tag',
49 | 'python setup.py sdist upload',
50 | ]
51 | sys.exit(sum(subprocess.call(shlex.split(cmd)) for cmd in commands))
52 |
53 |
54 | here = osp.dirname(osp.abspath(__file__))
55 |
56 |
57 | def customize(command_subclass):
58 | orig_run = command_subclass.run
59 |
60 | def customized_run(self):
61 | pyrcc = 'pyrcc{:d}'.format(PYQT_VERSION)
62 | if find_executable(pyrcc) is None:
63 | sys.stderr.write('Please install {:s} command.\n'.format(pyrcc))
64 | sys.stderr.write('(See https://github.com/wkentaro/labelme.git)\n')
65 | sys.exit(1)
66 | package_dir = osp.join(here, 'labelme')
67 | src = 'resources.qrc'
68 | dst = 'resources.py'
69 | cmd = '{pyrcc} -o {dst} {src}'.format(pyrcc=pyrcc, src=src, dst=dst)
70 | print('+ {:s}'.format(cmd))
71 | subprocess.call(shlex.split(cmd), cwd=package_dir)
72 | orig_run(self)
73 |
74 | command_subclass.run = customized_run
75 | return command_subclass
76 |
77 |
78 | @customize
79 | class CustomDevelopCommand(DevelopCommand):
80 | pass
81 |
82 |
83 | @customize
84 | class CustomInstallCommand(InstallCommand):
85 | pass
86 |
87 |
88 | setup(
89 | name='labelme',
90 | version=version,
91 | packages=find_packages(),
92 | cmdclass={
93 | 'develop': CustomDevelopCommand,
94 | 'install': CustomInstallCommand,
95 | },
96 | description='Annotation Tool for Object Segmentation.',
97 | long_description=open('README.md').read(),
98 | author='Kentaro Wada',
99 | author_email='www.kentaro.wada@gmail.com',
100 | url='https://github.com/wkentaro/labelme',
101 | install_requires=install_requires,
102 | license='GPLv3',
103 | keywords='Image Annotation, Machine Learning',
104 | classifiers=[
105 | 'Development Status :: 5 - Production/Stable',
106 | 'Intended Audience :: Developers',
107 | 'License :: OSI Approved :: MIT License',
108 | 'Operating System :: POSIX',
109 | 'Topic :: Internet :: WWW/HTTP',
110 | ],
111 | package_data={'labelme': ['icons/*', 'resources.qrc']},
112 | entry_points={'console_scripts': ['labelme=labelme.app:main']},
113 | scripts=[
114 | 'scripts/labelme_draw_json',
115 | 'scripts/labelme_json_to_dataset',
116 | 'scripts/labelme_on_docker',
117 | ],
118 | )
119 |
--------------------------------------------------------------------------------
/labelme/utils.py:
--------------------------------------------------------------------------------
1 | import base64
2 | try:
3 | import io
4 | except ImportError:
5 | import io as io
6 | import warnings
7 |
8 | import matplotlib.pyplot as plt
9 | import numpy as np
10 | import PIL.Image
11 | import PIL.ImageDraw
12 |
13 |
14 | def label_colormap(N=256):
15 |
16 | def bitget(byteval, idx):
17 | return ((byteval & (1 << idx)) != 0)
18 |
19 | cmap = np.zeros((N, 3))
20 | for i in range(0, N):
21 | id = i
22 | r, g, b = 0, 0, 0
23 | for j in range(0, 8):
24 | r = np.bitwise_or(r, (bitget(id, 0) << 7-j))
25 | g = np.bitwise_or(g, (bitget(id, 1) << 7-j))
26 | b = np.bitwise_or(b, (bitget(id, 2) << 7-j))
27 | id = (id >> 3)
28 | cmap[i, 0] = r
29 | cmap[i, 1] = g
30 | cmap[i, 2] = b
31 | cmap = cmap.astype(np.float32) / 255
32 | return cmap
33 |
34 |
35 | def labelcolormap(N=256):
36 | warnings.warn('labelcolormap is deprecated. Please use label_colormap.')
37 | return label_colormap(N=N)
38 |
39 |
40 | # similar function as skimage.color.label2rgb
41 | def label2rgb(lbl, img=None, n_labels=None, alpha=0.3, thresh_suppress=0):
42 | if n_labels is None:
43 | n_labels = len(np.unique(lbl))
44 |
45 | cmap = label_colormap(n_labels)
46 | cmap = (cmap * 255).astype(np.uint8)
47 |
48 | lbl_viz = cmap[lbl]
49 | lbl_viz[lbl == -1] = (0, 0, 0) # unlabeled
50 |
51 | if img is not None:
52 | img_gray = PIL.Image.fromarray(img).convert('LA')
53 | img_gray = np.asarray(img_gray.convert('RGB'))
54 | # img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
55 | # img_gray = cv2.cvtColor(img_gray, cv2.COLOR_GRAY2RGB)
56 | lbl_viz = alpha * lbl_viz + (1 - alpha) * img_gray
57 | lbl_viz = lbl_viz.astype(np.uint8)
58 |
59 | return lbl_viz
60 |
61 |
62 | def img_b64_to_array(img_b64):
63 | f = io.BytesIO()
64 | f.write(base64.b64decode(img_b64))
65 | img_arr = np.array(PIL.Image.open(f))
66 | return img_arr
67 |
68 |
69 | def polygons_to_mask(img_shape, polygons):
70 | mask = np.zeros(img_shape[:2], dtype=np.uint8)
71 | mask = PIL.Image.fromarray(mask)
72 | xy = list(map(tuple, polygons))
73 | PIL.ImageDraw.Draw(mask).polygon(xy=xy, outline=1, fill=1)
74 | mask = np.array(mask, dtype=bool)
75 | return mask
76 |
77 |
78 | def draw_label(label, img, label_names, colormap=None):
79 | plt.subplots_adjust(left=0, right=1, top=1, bottom=0,
80 | wspace=0, hspace=0)
81 | plt.margins(0, 0)
82 | plt.gca().xaxis.set_major_locator(plt.NullLocator())
83 | plt.gca().yaxis.set_major_locator(plt.NullLocator())
84 |
85 | if colormap is None:
86 | colormap = label_colormap(len(label_names))
87 |
88 | label_viz = label2rgb(label, img, n_labels=len(label_names))
89 | plt.imshow(label_viz)
90 | plt.axis('off')
91 |
92 | plt_handlers = []
93 | plt_titles = []
94 | for label_value, label_name in enumerate(label_names):
95 | fc = colormap[label_value]
96 | p = plt.Rectangle((0, 0), 1, 1, fc=fc)
97 | plt_handlers.append(p)
98 | plt_titles.append(label_name)
99 | plt.legend(plt_handlers, plt_titles, loc='lower right', framealpha=.5)
100 |
101 | f = io.BytesIO()
102 | plt.savefig(f, bbox_inches='tight', pad_inches=0)
103 | plt.cla()
104 | plt.close()
105 |
106 | out_size = (img.shape[1], img.shape[0])
107 | out = PIL.Image.open(f).resize(out_size, PIL.Image.BILINEAR).convert('RGB')
108 | out = np.asarray(out)
109 | return out
110 |
111 |
112 | def labelme_shapes_to_label(img_shape, shapes):
113 | label_name_to_val = {'background': 0}
114 | lbl = np.zeros(img_shape[:2], dtype=np.int32)
115 | for shape in shapes:
116 | polygons = shape['points']
117 | label_name = shape['label']
118 | if label_name in label_name_to_val:
119 | label_value = label_name_to_val[label_name]
120 | else:
121 | label_value = len(label_name_to_val)
122 | label_name_to_val[label_name] = label_value
123 | mask = polygons_to_mask(img_shape[:2], polygons)
124 | lbl[mask] = label_value
125 |
126 | lbl_names = [None] * (max(label_name_to_val.values()) + 1)
127 | for label_name, label_value in label_name_to_val.items():
128 | lbl_names[label_value] = label_name
129 |
130 | return lbl, lbl_names
131 |
--------------------------------------------------------------------------------
/labelme/shape.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # -*- coding: utf-8 -*-
3 | #
4 | # Copyright (C) 2011 Michael Pitidis, Hussein Abdulwahid.
5 | #
6 | # This file is part of Labelme.
7 | #
8 | # Labelme is free software: you can redistribute it and/or modify
9 | # it under the terms of the GNU General Public License as published by
10 | # the Free Software Foundation, either version 3 of the License, or
11 | # (at your option) any later version.
12 | #
13 | # Labelme is distributed in the hope that it will be useful,
14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | # GNU General Public License for more details.
17 | #
18 | # You should have received a copy of the GNU General Public License
19 | # along with Labelme. If not, see .
20 | #
21 |
22 | try:
23 | from PyQt5.QtGui import *
24 | from PyQt5.QtCore import *
25 | except ImportError:
26 | from PyQt4.QtGui import *
27 | from PyQt4.QtCore import *
28 |
29 |
30 | from .lib import distance
31 |
32 | # TODO:
33 | # - [opt] Store paths instead of creating new ones at each paint.
34 |
35 | DEFAULT_LINE_COLOR = QColor(0, 255, 0, 128)
36 | DEFAULT_FILL_COLOR = QColor(255, 0, 0, 128)
37 | DEFAULT_SELECT_LINE_COLOR = QColor(255, 255, 255)
38 | DEFAULT_SELECT_FILL_COLOR = QColor(0, 128, 255, 155)
39 | DEFAULT_VERTEX_FILL_COLOR = QColor(0, 255, 0, 255)
40 | DEFAULT_HVERTEX_FILL_COLOR = QColor(255, 0, 0)
41 |
42 | class Shape(object):
43 | P_SQUARE, P_ROUND = 0, 1
44 |
45 | MOVE_VERTEX, NEAR_VERTEX = 0, 1
46 |
47 | ## The following class variables influence the drawing
48 | ## of _all_ shape objects.
49 | line_color = DEFAULT_LINE_COLOR
50 | fill_color = DEFAULT_FILL_COLOR
51 | select_line_color = DEFAULT_SELECT_LINE_COLOR
52 | select_fill_color = DEFAULT_SELECT_FILL_COLOR
53 | vertex_fill_color = DEFAULT_VERTEX_FILL_COLOR
54 | hvertex_fill_color = DEFAULT_HVERTEX_FILL_COLOR
55 | point_type = P_ROUND
56 | point_size = 8
57 | scale = 1.0
58 |
59 | def __init__(self, label=None, line_color=None):
60 | self.label = label
61 | self.points = []
62 | self.fill = False
63 | self.selected = False
64 |
65 | self._highlightIndex = None
66 | self._highlightMode = self.NEAR_VERTEX
67 | self._highlightSettings = {
68 | self.NEAR_VERTEX: (4, self.P_ROUND),
69 | self.MOVE_VERTEX: (1.5, self.P_SQUARE),
70 | }
71 |
72 | self._closed = False
73 |
74 | if line_color is not None:
75 | # Override the class line_color attribute
76 | # with an object attribute. Currently this
77 | # is used for drawing the pending line a different color.
78 | self.line_color = line_color
79 |
80 | def close(self):
81 | assert len(self.points) == 1, 'Polygon should be created with point'
82 | self._closed = True
83 |
84 | def addPoint(self, point):
85 | self.points.append(point)
86 | self.close()
87 |
88 | def popPoint(self):
89 | if self.points:
90 | return self.points.pop()
91 | return None
92 |
93 | def isClosed(self):
94 | return self._closed
95 |
96 | def setOpen(self):
97 | self._closed = False
98 |
99 | def paint_bbox(self, painter):
100 | pen = QPen(Qt.red)
101 | font = QFont()
102 | font.setPointSize(20)
103 | # Try using integer sizes for smoother drawing(?)
104 | pen.setWidth(max(5, int(round(2.0 / self.scale))))
105 | painter.setPen(pen)
106 | painter.setFont(font)
107 |
108 | # draw a rectangle
109 | painter.drawText(20, 20, str(self.imgCnt))
110 | painter.drawRect(
111 | self.person_bbox[0], self.person_bbox[1], self.person_bbox[2], self.person_bbox[3])
112 |
113 | def paint(self, painter):
114 | if self.points:
115 | color = self.select_line_color if self.selected else self.line_color
116 | pen = QPen(color)
117 | font = QFont()
118 | font.setPointSize(20)
119 | # Try using integer sizes for smoother drawing(?)
120 | pen.setWidth(max(5, int(round(2.0 / self.scale))))
121 | painter.setPen(pen)
122 | painter.setFont(font)
123 |
124 | line_path = QPainterPath()
125 | vrtx_path = QPainterPath()
126 | # draw a rectangle
127 | #painter.drawText(20, 20, str(self.imgCnt))
128 | #painter.drawRect(
129 | # self.person_bbox[0], self.person_bbox[1], self.person_bbox[2], self.person_bbox[3])
130 |
131 | line_path.moveTo(self.points[0])
132 | # Uncommenting the following line will draw 2 paths
133 | # for the 1st vertex, and make it non-filled, which
134 | # may be desirable.
135 | #self.drawVertex(vrtx_path, 0)
136 |
137 | for i, p in enumerate(self.points):
138 | line_path.lineTo(p)
139 | self.drawVertex(vrtx_path, i)
140 | if self.isClosed():
141 | line_path.lineTo(self.points[0])
142 | painter.drawPath(line_path)
143 | painter.drawPath(vrtx_path)
144 | painter.fillPath(vrtx_path, self.vertex_fill_color)
145 | if self.fill:
146 | color = self.select_fill_color if self.selected else self.fill_color
147 | painter.fillPath(line_path, color)
148 |
149 | def drawVertex(self, path, i):
150 | d = self.point_size / self.scale
151 | shape = self.point_type
152 | point = self.points[i]
153 | if i == self._highlightIndex:
154 | size, shape = self._highlightSettings[self._highlightMode]
155 | d *= size
156 | if self._highlightIndex is not None:
157 | self.vertex_fill_color = self.hvertex_fill_color
158 | else:
159 | self.vertex_fill_color = Shape.vertex_fill_color
160 | if shape == self.P_SQUARE:
161 | path.addRect(point.x() - d/2, point.y() - d/2, d, d)
162 | elif shape == self.P_ROUND:
163 | path.addEllipse(point, d/2.0, d/2.0)
164 | else:
165 | assert False, "unsupported vertex shape"
166 |
167 | def nearestVertex(self, point, epsilon):
168 | min_distance = float('inf')
169 | min_i = None
170 | for i, p in enumerate(self.points):
171 | dist = distance(p - point)
172 | if dist <= epsilon and dist < min_distance:
173 | min_distance = dist
174 | min_i = i
175 | return min_i
176 |
177 | def containsPoint(self, point):
178 | return self.makePath().contains(point)
179 |
180 | def makePath(self):
181 | path = QPainterPath(self.points[0])
182 | for p in self.points[1:]:
183 | path.lineTo(p)
184 | return path
185 |
186 | def boundingRect(self):
187 | return self.makePath().boundingRect()
188 |
189 | def moveBy(self, offset):
190 | self.points = [p + offset for p in self.points]
191 |
192 | def moveVertexBy(self, i, offset):
193 | self.points[i] = self.points[i] + offset
194 |
195 | def highlightVertex(self, i, action):
196 | self._highlightIndex = i
197 | self._highlightMode = action
198 |
199 | def highlightClear(self):
200 | self._highlightIndex = None
201 |
202 | def copy(self):
203 | shape = Shape("Copy of %s" % self.label )
204 | shape.points= [p for p in self.points]
205 | shape.fill = self.fill
206 | shape.selected = self.selected
207 | shape._closed = self._closed
208 | if self.line_color != Shape.line_color:
209 | shape.line_color = self.line_color
210 | if self.fill_color != Shape.fill_color:
211 | shape.fill_color = self.fill_color
212 | return shape
213 |
214 | def __len__(self):
215 | return len(self.points)
216 |
217 | def __getitem__(self, key):
218 | return self.points[key]
219 |
220 | def __setitem__(self, key, value):
221 | self.points[key] = value
222 |
223 |
--------------------------------------------------------------------------------
/labelme/icons/open.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/labelme/icons/done.svg:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
401 |
--------------------------------------------------------------------------------
/labelme/canvas.py:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (C) 2011 Michael Pitidis, Hussein Abdulwahid.
3 | #
4 | # This file is part of Labelme.
5 | #
6 | # Labelme is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # Labelme is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with Labelme. If not, see .
18 | #
19 |
20 | from __future__ import print_function
21 |
22 | import sys
23 |
24 | try:
25 | from PyQt5.QtGui import *
26 | from PyQt5.QtCore import *
27 | from PyQt5.QtWidgets import *
28 | PYQT5 = True
29 | except ImportError:
30 | from PyQt4.QtGui import *
31 | from PyQt4.QtCore import *
32 | PYQT5 = False
33 |
34 | from labelme.shape import Shape
35 | from labelme.lib import distance
36 |
37 | # TODO:
38 | # - [maybe] Find optimal epsilon value.
39 |
40 | CURSOR_DEFAULT = Qt.ArrowCursor
41 | CURSOR_POINT = Qt.PointingHandCursor
42 | CURSOR_DRAW = Qt.CrossCursor
43 | CURSOR_MOVE = Qt.ClosedHandCursor
44 | CURSOR_GRAB = Qt.OpenHandCursor
45 |
46 | #class Canvas(QGLWidget):
47 | class Canvas(QWidget):
48 | zoomRequest = pyqtSignal(int)
49 | scrollRequest = pyqtSignal(int, int)
50 | newShape = pyqtSignal()
51 | selectionChanged = pyqtSignal(bool)
52 | shapeMoved = pyqtSignal()
53 | drawingPolygon = pyqtSignal(bool)
54 |
55 | CREATE, EDIT = 0, 1
56 |
57 | epsilon = 11.0
58 |
59 | def __init__(self, *args, **kwargs):
60 | super(Canvas, self).__init__(*args, **kwargs)
61 | # Initialise local state.
62 | self.mode = self.EDIT
63 | self.shapes = []
64 | self.current = None
65 | self.selectedShape=None # save the selected shape here
66 | self.selectedShapeCopy=None
67 | self.lineColor = QColor(0, 0, 255)
68 | self.line = Shape(line_color=self.lineColor)
69 | self.prevPoint = QPointF()
70 | self.offsets = QPointF(), QPointF()
71 | self.scale = 1.0
72 | self.pixmap = QPixmap()
73 | self.visible = {}
74 | self._hideBackround = False
75 | self.hideBackround = False
76 | self.hShape = None
77 | self.hVertex = None
78 | self._painter = QPainter()
79 | self._cursor = CURSOR_DEFAULT
80 | self.paint_info = False
81 | # Menus:
82 | self.menus = (QMenu(), QMenu())
83 | # Set widget options.
84 | self.setMouseTracking(True)
85 | self.setFocusPolicy(Qt.WheelFocus)
86 |
87 | def enterEvent(self, ev):
88 | self.overrideCursor(self._cursor)
89 |
90 | def leaveEvent(self, ev):
91 | self.restoreCursor()
92 |
93 | def focusOutEvent(self, ev):
94 | self.restoreCursor()
95 |
96 | def isVisible(self, shape):
97 | return self.visible.get(shape, True)
98 |
99 | def drawing(self):
100 | return self.mode == self.CREATE
101 |
102 | def editing(self):
103 | return self.mode == self.EDIT
104 |
105 | def setEditing(self, value=True):
106 | self.mode = self.EDIT if value else self.CREATE
107 | if not value: # Create
108 | self.unHighlight()
109 | self.deSelectShape()
110 |
111 | def unHighlight(self):
112 | if self.hShape:
113 | self.hShape.highlightClear()
114 | self.hVertex = self.hShape = None
115 |
116 | def selectedVertex(self):
117 | return self.hVertex is not None
118 |
119 | def mouseMoveEvent(self, ev):
120 | """Update line with last point and current coordinates."""
121 | if PYQT5:
122 | pos = self.transformPos(ev.pos())
123 | else:
124 | pos = self.transformPos(ev.posF())
125 |
126 | self.restoreCursor()
127 |
128 | # Polygon drawing.
129 | if self.drawing():
130 | self.overrideCursor(CURSOR_DRAW)
131 | if self.current:
132 | color = self.lineColor
133 | if self.outOfPixmap(pos):
134 | # Don't allow the user to draw outside the pixmap.
135 | # Project the point to the pixmap's edges.
136 | pos = self.intersectionPoint(self.current[-1], pos)
137 | elif len(self.current) > 1 and self.closeEnough(pos, self.current[0]):
138 | # Attract line to starting point and colorise to alert the user:
139 | pos = self.current[0]
140 | color = self.current.line_color
141 | self.overrideCursor(CURSOR_POINT)
142 | self.current.highlightVertex(0, Shape.NEAR_VERTEX)
143 | self.line[1] = pos
144 | self.line.line_color = color
145 | self.repaint()
146 | self.current.highlightClear()
147 | return
148 |
149 | # Polygon copy moving.
150 | if Qt.RightButton & ev.buttons():
151 | if self.selectedShapeCopy and self.prevPoint:
152 | self.overrideCursor(CURSOR_MOVE)
153 | self.boundedMoveShape(self.selectedShapeCopy, pos)
154 | self.repaint()
155 | elif self.selectedShape:
156 | self.selectedShapeCopy = self.selectedShape.copy()
157 | self.repaint()
158 | return
159 |
160 | # Polygon/Vertex moving.
161 | if Qt.LeftButton & ev.buttons():
162 | if self.selectedVertex():
163 | self.boundedMoveVertex(pos)
164 | self.shapeMoved.emit()
165 | self.repaint()
166 | elif self.selectedShape and self.prevPoint:
167 | self.overrideCursor(CURSOR_MOVE)
168 | self.boundedMoveShape(self.selectedShape, pos)
169 | self.shapeMoved.emit()
170 | self.repaint()
171 | return
172 |
173 | # Just hovering over the canvas, 2 posibilities:
174 | # - Highlight shapes
175 | # - Highlight vertex
176 | # Update shape/vertex fill and tooltip value accordingly.
177 | self.setToolTip("Image")
178 | for shape in reversed([s for s in self.shapes if self.isVisible(s)]):
179 | # Look for a nearby vertex to highlight. If that fails,
180 | # check if we happen to be inside a shape.
181 | index = shape.nearestVertex(pos, self.epsilon)
182 | if index is not None:
183 | if self.selectedVertex():
184 | self.hShape.highlightClear()
185 | self.hVertex, self.hShape = index, shape
186 | shape.highlightVertex(index, shape.MOVE_VERTEX)
187 | self.overrideCursor(CURSOR_POINT)
188 | self.setToolTip("Click & drag to move point")
189 | self.setStatusTip(self.toolTip())
190 | self.update()
191 | break
192 | elif shape.containsPoint(pos):
193 | if self.selectedVertex():
194 | self.hShape.highlightClear()
195 | self.hVertex, self.hShape = None, shape
196 | self.setToolTip("Click & drag to move shape '%s'" % shape.label)
197 | self.setStatusTip(self.toolTip())
198 | self.overrideCursor(CURSOR_GRAB)
199 | self.update()
200 | break
201 | else: # Nothing found, clear highlights, reset state.
202 | if self.hShape:
203 | self.hShape.highlightClear()
204 | self.update()
205 | self.hVertex, self.hShape = None, None
206 |
207 | def mousePressEvent(self, ev):
208 | if PYQT5:
209 | pos = self.transformPos(ev.pos())
210 | else:
211 | pos = self.transformPos(ev.posF())
212 | if ev.button() == Qt.LeftButton:
213 | if self.drawing():
214 | if self.current:
215 | try:
216 | self.current.addPoint(self.line[1])
217 | except Exception as e:
218 | print(e, file=sys.stderr)
219 | return
220 | self.line[0] = self.current[-1]
221 | if self.current.isClosed():
222 | self.finalise()
223 | elif not self.outOfPixmap(pos):
224 | self.current = Shape()
225 | self.current.addPoint(pos)
226 | #self.current.person_box = bbox
227 | self.current.imgCnt = self.imgCnt
228 | self.current.person_bbox = self.person_bbox
229 | # choose color
230 | self.current.line_color = Qt.red
231 | self.line.points = [pos, pos]
232 | self.setHiding()
233 | self.drawingPolygon.emit(True)
234 | self.update()
235 | if self.current.isClosed():
236 | self.finalise()
237 | else:
238 | self.selectShapePoint(pos)
239 | self.prevPoint = pos
240 | self.repaint()
241 | elif ev.button() == Qt.RightButton and self.editing():
242 | self.selectShapePoint(pos)
243 | self.prevPoint = pos
244 | self.repaint()
245 |
246 | def mouseReleaseEvent(self, ev):
247 | if ev.button() == Qt.RightButton:
248 | menu = self.menus[bool(self.selectedShapeCopy)]
249 | self.restoreCursor()
250 | if not menu.exec_(self.mapToGlobal(ev.pos()))\
251 | and self.selectedShapeCopy:
252 | # Cancel the move by deleting the shadow copy.
253 | self.selectedShapeCopy = None
254 | self.repaint()
255 | elif ev.button() == Qt.LeftButton and self.selectedShape:
256 | self.overrideCursor(CURSOR_GRAB)
257 |
258 | def endMove(self, copy=False):
259 | assert self.selectedShape and self.selectedShapeCopy
260 | shape = self.selectedShapeCopy
261 | #del shape.fill_color
262 | #del shape.line_color
263 | if copy:
264 | self.shapes.append(shape)
265 | self.selectedShape.selected = False
266 | self.selectedShape = shape
267 | self.repaint()
268 | else:
269 | shape.label = self.selectedShape.label
270 | self.deleteSelected()
271 | self.shapes.append(shape)
272 | self.selectedShapeCopy = None
273 |
274 | def hideBackroundShapes(self, value):
275 | self.hideBackround = value
276 | if self.selectedShape:
277 | # Only hide other shapes if there is a current selection.
278 | # Otherwise the user will not be able to select a shape.
279 | self.setHiding(True)
280 | self.repaint()
281 |
282 | def setHiding(self, enable=True):
283 | self._hideBackround = self.hideBackround if enable else False
284 |
285 | def canCloseShape(self):
286 | return self.drawing() and self.current and len(self.current) > 2
287 |
288 | def mouseDoubleClickEvent(self, ev):
289 | # We need at least 4 points here, since the mousePress handler
290 | # adds an extra one before this handler is called.
291 | if self.canCloseShape() and len(self.current) > 3:
292 | self.current.popPoint()
293 | self.finalise()
294 |
295 | def selectShape(self, shape):
296 | self.deSelectShape()
297 | shape.selected = True
298 | self.selectedShape = shape
299 | self.setHiding()
300 | self.selectionChanged.emit(True)
301 | self.update()
302 |
303 | def selectShapePoint(self, point):
304 | """Select the first shape created which contains this point."""
305 | self.deSelectShape()
306 | if self.selectedVertex(): # A vertex is marked for selection.
307 | index, shape = self.hVertex, self.hShape
308 | shape.highlightVertex(index, shape.MOVE_VERTEX)
309 | return
310 | for shape in reversed(self.shapes):
311 | if self.isVisible(shape) and shape.containsPoint(point):
312 | shape.selected = True
313 | self.selectedShape = shape
314 | self.calculateOffsets(shape, point)
315 | self.setHiding()
316 | self.selectionChanged.emit(True)
317 | return
318 |
319 | def calculateOffsets(self, shape, point):
320 | rect = shape.boundingRect()
321 | x1 = rect.x() - point.x()
322 | y1 = rect.y() - point.y()
323 | x2 = (rect.x() + rect.width()) - point.x()
324 | y2 = (rect.y() + rect.height()) - point.y()
325 | self.offsets = QPointF(x1, y1), QPointF(x2, y2)
326 |
327 | def boundedMoveVertex(self, pos):
328 | index, shape = self.hVertex, self.hShape
329 | point = shape[index]
330 | if self.outOfPixmap(pos):
331 | pos = self.intersectionPoint(point, pos)
332 | shape.moveVertexBy(index, pos - point)
333 |
334 | def boundedMoveShape(self, shape, pos):
335 | if self.outOfPixmap(pos):
336 | return False # No need to move
337 | o1 = pos + self.offsets[0]
338 | if self.outOfPixmap(o1):
339 | pos -= QPointF(min(0, o1.x()), min(0, o1.y()))
340 | o2 = pos + self.offsets[1]
341 | if self.outOfPixmap(o2):
342 | pos += QPointF(min(0, self.pixmap.width() - o2.x()),
343 | min(0, self.pixmap.height()- o2.y()))
344 | # The next line tracks the new position of the cursor
345 | # relative to the shape, but also results in making it
346 | # a bit "shaky" when nearing the border and allows it to
347 | # go outside of the shape's area for some reason. XXX
348 | #self.calculateOffsets(self.selectedShape, pos)
349 | dp = pos - self.prevPoint
350 | if dp:
351 | shape.moveBy(dp)
352 | self.prevPoint = pos
353 | return True
354 | return False
355 |
356 | def deSelectShape(self):
357 | if self.selectedShape:
358 | self.selectedShape.selected = False
359 | self.selectedShape = None
360 | self.setHiding(False)
361 | self.selectionChanged.emit(False)
362 | self.update()
363 |
364 | def deleteSelected(self):
365 | if self.selectedShape:
366 | shape = self.selectedShape
367 | print('Delete ' + shape.label)
368 | self.shapes.remove(self.selectedShape)
369 | self.selectedShape = None
370 | self.update()
371 | return shape
372 |
373 | def copySelectedShape(self):
374 | if self.selectedShape:
375 | shape = self.selectedShape.copy()
376 | self.deSelectShape()
377 | self.shapes.append(shape)
378 | shape.selected = True
379 | self.selectedShape = shape
380 | self.boundedShiftShape(shape)
381 | return shape
382 |
383 | def boundedShiftShape(self, shape):
384 | # Try to move in one direction, and if it fails in another.
385 | # Give up if both fail.
386 | point = shape[0]
387 | offset = QPointF(2.0, 2.0)
388 | self.calculateOffsets(shape, point)
389 | self.prevPoint = point
390 | if not self.boundedMoveShape(shape, point - offset):
391 | self.boundedMoveShape(shape, point + offset)
392 |
393 | def paint_bbox(self, painter):
394 | pen = QPen(Qt.red)
395 | font = QFont()
396 | font.setPointSize(20)
397 | # Try using integer sizes for smoother drawing(?)
398 | pen.setWidth(max(5, int(round(2.0 / self.scale))))
399 | painter.setPen(pen)
400 | painter.setFont(font)
401 |
402 | # draw a rectangle
403 | painter.drawText(10, 15, str(self.imgCnt))
404 | font.setPointSize(15)
405 | painter.setFont(font)
406 |
407 | painter.drawText(30, 15, 'person: '+str(self.person_id))
408 | painter.drawText(150, 15, 'prog: %d/%d' % tuple(self.progress))
409 |
410 | painter.drawRect(
411 | self.person_bbox[0], self.person_bbox[1], self.person_bbox[2], self.person_bbox[3])
412 |
413 | def paintEvent(self, event):
414 | if not self.pixmap:
415 | return super(Canvas, self).paintEvent(event)
416 |
417 | p = self._painter
418 | p.begin(self)
419 | p.setRenderHint(QPainter.Antialiasing)
420 | p.setRenderHint(QPainter.HighQualityAntialiasing)
421 | p.setRenderHint(QPainter.SmoothPixmapTransform)
422 |
423 | p.scale(self.scale, self.scale)
424 | p.translate(self.offsetToCenter())
425 |
426 | p.drawPixmap(0, 0, self.pixmap)
427 | if self.paint_info:
428 | self.paint_bbox(p)
429 | #p.end()
430 |
431 | Shape.scale = self.scale
432 | for shape in self.shapes:
433 | if (shape.selected or not self._hideBackround) and self.isVisible(shape):
434 | shape.fill = shape.selected or shape == self.hShape
435 | if shape.label and 'Empty' in shape.label:
436 | continue
437 | shape.paint(p)
438 | if self.current:
439 | self.current.paint(p)
440 | self.line.paint(p)
441 | if self.selectedShapeCopy:
442 | self.selectedShapeCopy.paint(p)
443 |
444 | p.end()
445 |
446 | def transformPos(self, point):
447 | """Convert from widget-logical coordinates to painter-logical coordinates."""
448 | return point / self.scale - self.offsetToCenter()
449 |
450 | def offsetToCenter(self):
451 | s = self.scale
452 | area = super(Canvas, self).size()
453 | w, h = self.pixmap.width() * s, self.pixmap.height() * s
454 | aw, ah = area.width(), area.height()
455 | x = (aw-w)/(2*s) if aw > w else 0
456 | y = (ah-h)/(2*s) if ah > h else 0
457 | return QPointF(x, y)
458 |
459 | def outOfPixmap(self, p):
460 | w, h = self.pixmap.width(), self.pixmap.height()
461 | return not (0 <= p.x() <= w and 0 <= p.y() <= h)
462 |
463 | def finalise(self):
464 | assert self.current
465 | self.current.close()
466 | self.shapes.append(self.current)
467 | self.current = None
468 | self.setHiding(False)
469 | self.newShape.emit()
470 | self.update()
471 |
472 | def closeEnough(self, p1, p2):
473 | #d = distance(p1 - p2)
474 | #m = (p1-p2).manhattanLength()
475 | #print "d %.2f, m %d, %.2f" % (d, m, d - m)
476 | return distance(p1 - p2) < self.epsilon
477 |
478 | def intersectionPoint(self, p1, p2):
479 | # Cycle through each image edge in clockwise fashion,
480 | # and find the one intersecting the current line segment.
481 | # http://paulbourke.net/geometry/lineline2d/
482 | size = self.pixmap.size()
483 | points = [(0,0),
484 | (size.width(), 0),
485 | (size.width(), size.height()),
486 | (0, size.height())]
487 | x1, y1 = p1.x(), p1.y()
488 | x2, y2 = p2.x(), p2.y()
489 | d, i, (x, y) = min(self.intersectingEdges((x1, y1), (x2, y2), points))
490 | x3, y3 = points[i]
491 | x4, y4 = points[(i+1)%4]
492 | if (x, y) == (x1, y1):
493 | # Handle cases where previous point is on one of the edges.
494 | if x3 == x4:
495 | return QPointF(x3, min(max(0, y2), max(y3, y4)))
496 | else: # y3 == y4
497 | return QPointF(min(max(0, x2), max(x3, x4)), y3)
498 | return QPointF(x, y)
499 |
500 | def intersectingEdges(self, point1, point2, points):
501 | """For each edge formed by `points', yield the intersection
502 | with the line segment `(x1,y1) - (x2,y2)`, if it exists.
503 | Also return the distance of `(x2,y2)' to the middle of the
504 | edge along with its index, so that the one closest can be chosen."""
505 | (x1, y1) = point1
506 | (x2, y2) = point2
507 | for i in range(4):
508 | x3, y3 = points[i]
509 | x4, y4 = points[(i+1) % 4]
510 | denom = (y4-y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)
511 | nua = (x4-x3) * (y1-y3) - (y4-y3) * (x1-x3)
512 | nub = (x2-x1) * (y1-y3) - (y2-y1) * (x1-x3)
513 | if denom == 0:
514 | # This covers two cases:
515 | # nua == nub == 0: Coincident
516 | # otherwise: Parallel
517 | continue
518 | ua, ub = nua / denom, nub / denom
519 | if 0 <= ua <= 1 and 0 <= ub <= 1:
520 | x = x1 + ua * (x2 - x1)
521 | y = y1 + ua * (y2 - y1)
522 | m = QPointF((x3 + x4)/2, (y3 + y4)/2)
523 | d = distance(m - QPointF(x2, y2))
524 | yield d, i, (x, y)
525 |
526 | # These two, along with a call to adjustSize are required for the
527 | # scroll area.
528 | def sizeHint(self):
529 | return self.minimumSizeHint()
530 |
531 | def minimumSizeHint(self):
532 | if self.pixmap:
533 | return self.scale * self.pixmap.size()
534 | return super(Canvas, self).minimumSizeHint()
535 |
536 | def wheelEvent(self, ev):
537 | if PYQT5:
538 | mods = ev.modifiers()
539 | delta = ev.pixelDelta()
540 | if Qt.ControlModifier == int(mods): # with Ctrl/Command key
541 | # zoom
542 | self.zoomRequest.emit(delta.y())
543 | else:
544 | # scroll
545 | self.scrollRequest.emit(delta.x(), Qt.Horizontal)
546 | self.scrollRequest.emit(delta.y(), Qt.Vertical)
547 | else:
548 | if ev.orientation() == Qt.Vertical:
549 | mods = ev.modifiers()
550 | if Qt.ControlModifier == int(mods): # with Ctrl/Command key
551 | self.zoomRequest.emit(ev.delta())
552 | else:
553 | self.scrollRequest.emit(ev.delta(),
554 | Qt.Horizontal if (Qt.ShiftModifier == int(mods))\
555 | else Qt.Vertical)
556 | else:
557 | self.scrollRequest.emit(ev.delta(), Qt.Horizontal)
558 | ev.accept()
559 |
560 | def keyPressEvent(self, ev):
561 | key = ev.key()
562 | if key == Qt.Key_Escape and self.current:
563 | self.current = None
564 | self.drawingPolygon.emit(False)
565 | self.update()
566 | elif key == Qt.Key_Return and self.canCloseShape():
567 | self.finalise()
568 |
569 | def setLastLabel(self, text):
570 | assert text
571 | self.shapes[-1].label = text
572 | return self.shapes[-1]
573 |
574 | def undoLastLine(self):
575 | assert self.shapes
576 | self.current = self.shapes.pop()
577 | self.current.setOpen()
578 | self.line.points = [self.current[-1], self.current[0]]
579 | self.drawingPolygon.emit(True)
580 |
581 | def undoWrongLabel(self):
582 | assert self.shapes
583 | self.current = self.shapes.pop()
584 | self.current = None
585 |
586 | #self.current.setOpen()
587 | self.line.points = []
588 | self.drawingPolygon.emit(False)
589 |
590 | def loadPixmap(self, pixmap):
591 | self.pixmap = pixmap
592 | self.shapes = []
593 | self.repaint()
594 |
595 | def loadShapes(self, shapes):
596 | self.shapes = list(shapes)
597 | self.current = None
598 | self.repaint()
599 |
600 | def setShapeVisible(self, shape, value):
601 | self.visible[shape] = value
602 | self.repaint()
603 |
604 | def overrideCursor(self, cursor):
605 | self.restoreCursor()
606 | self._cursor = cursor
607 | QApplication.setOverrideCursor(cursor)
608 |
609 | def restoreCursor(self):
610 | QApplication.restoreOverrideCursor()
611 |
612 | def resetState(self):
613 | self.restoreCursor()
614 | self.pixmap = None
615 | self.update()
616 |
617 |
--------------------------------------------------------------------------------
/labelme/icons/save.svg:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
680 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------