├── helpers
├── __init__.py
├── pascal_map.npy
├── helpers.py
└── annotools.py
├── networks
├── __init__.py
├── classifiers.py
├── dextr.py
└── resnet.py
├── doc
├── dextr.png
└── github_teaser.gif
├── sample_images
├── bear.jpg
├── people.jpg
├── plane.jpg
├── skater.jpg
├── dog-cat.jpg
└── tea_boxes.jpg
├── mypath.py
├── models
└── download_dextr_model.sh
├── anno_cfg.yml
├── .gitignore
├── conda_env.yml
├── README.md
├── annotate.py
└── LICENSE
/helpers/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/networks/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/doc/dextr.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/karan-shr/DEXTR-AnnoTool/HEAD/doc/dextr.png
--------------------------------------------------------------------------------
/doc/github_teaser.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/karan-shr/DEXTR-AnnoTool/HEAD/doc/github_teaser.gif
--------------------------------------------------------------------------------
/helpers/pascal_map.npy:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/karan-shr/DEXTR-AnnoTool/HEAD/helpers/pascal_map.npy
--------------------------------------------------------------------------------
/sample_images/bear.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/karan-shr/DEXTR-AnnoTool/HEAD/sample_images/bear.jpg
--------------------------------------------------------------------------------
/sample_images/people.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/karan-shr/DEXTR-AnnoTool/HEAD/sample_images/people.jpg
--------------------------------------------------------------------------------
/sample_images/plane.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/karan-shr/DEXTR-AnnoTool/HEAD/sample_images/plane.jpg
--------------------------------------------------------------------------------
/sample_images/skater.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/karan-shr/DEXTR-AnnoTool/HEAD/sample_images/skater.jpg
--------------------------------------------------------------------------------
/sample_images/dog-cat.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/karan-shr/DEXTR-AnnoTool/HEAD/sample_images/dog-cat.jpg
--------------------------------------------------------------------------------
/mypath.py:
--------------------------------------------------------------------------------
1 |
2 | class Path(object):
3 | @staticmethod
4 | def models_dir():
5 | return 'models/'
6 |
--------------------------------------------------------------------------------
/sample_images/tea_boxes.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/karan-shr/DEXTR-AnnoTool/HEAD/sample_images/tea_boxes.jpg
--------------------------------------------------------------------------------
/models/download_dextr_model.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Model trained on PASCAL + SBD
4 | wget https://data.vision.ee.ethz.ch/csergi/share/DEXTR/dextr_pascal-sbd.h5
5 |
--------------------------------------------------------------------------------
/anno_cfg.yml:
--------------------------------------------------------------------------------
1 | #-----------------------------------------------anno_cfg.yml------------------------------------------------------------
2 | # Summary:
3 | # - this is the YAML configuration file where the settings for annotation are stored.
4 | # - please edit the file accordingly to your annotation setup.
5 | #-----------------------------------------------------------------------------------------------------------------------
6 |
7 | # Required parameters to be set by user
8 | required:
9 | source: ./sample_images # path to the dir containing images to be annotated
10 | destination: ./sample_images/segMasks # path to the dir where the generated masks should be saved
11 |
12 | # Optional parameters
13 | optional:
14 | update: true # set to True if more images were added to source folder after initial run
15 | mask_suffix: _mask # e.g. if source file: img_01.jpg then mask file: img_01_mask.jpg
16 | save_format: png # supports npy and png, (jpg not ideal)
17 |
18 | # ADMIN parameters (CAUTION: Don't edit unless you are sure what you are doing)
19 | admin:
20 | progress_file: .anno_prog # file used for tracking annotation progress, saved in the source folder
21 | reset_progress: false # set True to reset annotation progress i.e. to start over.
22 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # User specified
2 | models/
3 |
4 |
5 | # Byte-compiled / optimized / DLL files
6 | __pycache__/
7 | *.py[cod]
8 | *$py.class
9 | *.pth
10 |
11 | # C extensions
12 | *.so
13 |
14 | # Distribution / packaging
15 | .Python
16 | env/
17 | build/
18 | develop-eggs/
19 | dist/
20 | downloads/
21 | eggs/
22 | .eggs/
23 | lib/
24 | lib64/
25 | parts/
26 | sdist/
27 | var/
28 | wheels/
29 | *.egg-info/
30 | .installed.cfg
31 | *.egg
32 |
33 | # PyInstaller
34 | # Usually these files are written by a python script from a template
35 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
36 | *.manifest
37 | *.spec
38 |
39 | # Installer logs
40 | pip-log.txt
41 | pip-delete-this-directory.txt
42 |
43 | # Unit test / coverage reports
44 | htmlcov/
45 | .tox/
46 | .coverage
47 | .coverage.*
48 | .cache
49 | nosetests.xml
50 | coverage.xml
51 | *.cover
52 | .hypothesis/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 |
62 | # Flask stuff:
63 | instance/
64 | .webassets-cache
65 |
66 | # Scrapy stuff:
67 | .scrapy
68 |
69 | # Sphinx documentation
70 | docs/_build/
71 |
72 | # PyBuilder
73 | target/
74 |
75 | # Jupyter Notebook
76 | .ipynb_checkpoints
77 |
78 | # pyenv
79 | .python-version
80 |
81 | # celery beat schedule file
82 | celerybeat-schedule
83 |
84 | # SageMath parsed files
85 | *.sage.py
86 |
87 | # dotenv
88 | .env
89 |
90 | # virtualenv
91 | .venv
92 | venv/
93 | ENV/
94 |
95 | # Spyder project settings
96 | .spyderproject
97 | .spyproject
98 |
99 | # Pycharm project settings
100 | .idea
101 |
102 | # Rope project settings
103 | .ropeproject
104 |
105 | # mkdocs documentation
106 | /site
107 |
108 | # mypy
109 | .mypy_cache/
110 |
--------------------------------------------------------------------------------
/conda_env.yml:
--------------------------------------------------------------------------------
1 | name: dextr_annotool
2 | channels:
3 | - conda-forge
4 | - defaults
5 | dependencies:
6 | - _tflow_select=2.1.0=gpu
7 | - absl-py=0.7.1=py36_0
8 | - astor=0.7.1=py36_0
9 | - blas=1.0=mkl
10 | - bzip2=1.0.6=h14c3975_5
11 | - c-ares=1.15.0=h7b6447c_1
12 | - ca-certificates=2019.5.15=0
13 | - cairo=1.14.12=h8948797_3
14 | - certifi=2019.3.9=py36_0
15 | - cudatoolkit=9.0=h13b8566_0
16 | - cudnn=7.6.0=cuda9.0_0
17 | - cupti=9.0.176=0
18 | - cycler=0.10.0=py36_0
19 | - dbus=1.13.6=h746ee38_0
20 | - expat=2.2.6=he6710b0_0
21 | - ffmpeg=4.0=hcdf2ecd_0
22 | - fontconfig=2.13.0=h9420a91_0
23 | - freeglut=3.0.0=hf484d3e_5
24 | - freetype=2.9.1=h8a8886c_1
25 | - gast=0.2.2=py36_0
26 | - glib=2.56.2=hd408876_0
27 | - graphite2=1.3.13=h23475e2_0
28 | - grpcio=1.16.1=py36hf8bcb03_1
29 | - gst-plugins-base=1.14.0=hbbd80ab_1
30 | - gstreamer=1.14.0=hb453b48_1
31 | - h5py=2.8.0=py36h989c5e5_3
32 | - harfbuzz=1.8.8=hffaf4a1_0
33 | - hdf5=1.10.2=hba1933b_1
34 | - icu=58.2=h9c2bf20_1
35 | - intel-openmp=2019.4=243
36 | - jasper=2.0.14=h07fcdf6_1
37 | - jpeg=9b=h024ee3a_2
38 | - keras=2.2.4=0
39 | - keras-applications=1.0.8=py_0
40 | - keras-base=2.2.4=py36_0
41 | - keras-preprocessing=1.1.0=py_1
42 | - kiwisolver=1.1.0=py36he6710b0_0
43 | - libedit=3.1.20181209=hc058e9b_0
44 | - libffi=3.2.1=hd88cf55_4
45 | - libgcc-ng=9.1.0=hdf63c60_0
46 | - libgfortran-ng=7.3.0=hdf63c60_0
47 | - libglu=9.0.0=hf484d3e_1
48 | - libopencv=3.4.2=hb342d67_1
49 | - libopus=1.3=h7b6447c_0
50 | - libpng=1.6.37=hbc83047_0
51 | - libprotobuf=3.8.0=hd408876_0
52 | - libstdcxx-ng=9.1.0=hdf63c60_0
53 | - libtiff=4.0.10=h2733197_2
54 | - libuuid=1.0.3=h1bed415_2
55 | - libvpx=1.7.0=h439df22_0
56 | - libxcb=1.13=h1bed415_1
57 | - libxml2=2.9.9=he19cac6_0
58 | - markdown=3.1.1=py36_0
59 | - matplotlib=3.1.0=py36h5429711_0
60 | - mkl=2019.4=243
61 | - mkl_fft=1.0.12=py36ha843d7b_0
62 | - mkl_random=1.0.2=py36hd81dba3_0
63 | - mock=3.0.5=py36_0
64 | - ncurses=6.1=he6710b0_1
65 | - numpy=1.16.4=py36h7e9f1db_0
66 | - numpy-base=1.16.4=py36hde5b4d6_0
67 | - olefile=0.46=py36_0
68 | - opencv=3.4.2=py36h6fd60c2_1
69 | - openssl=1.1.1c=h7b6447c_1
70 | - pcre=8.43=he6710b0_0
71 | - pillow=6.0.0=py36h34e0f95_0
72 | - pip=19.1.1=py36_0
73 | - pixman=0.38.0=h7b6447c_0
74 | - protobuf=3.8.0=py36he6710b0_0
75 | - py-opencv=3.4.2=py36hb342d67_1
76 | - pyparsing=2.4.0=py_0
77 | - pyqt=5.9.2=py36h05f1152_2
78 | - python=3.6.8=h0371630_0
79 | - python-dateutil=2.8.0=py36_0
80 | - pytz=2019.1=py_0
81 | - pyyaml=5.1=py36h7b6447c_0
82 | - qt=5.9.7=h5867ecd_1
83 | - readline=7.0=h7b6447c_5
84 | - ruamel=1.0=py36_0
85 | - ruamel.yaml=0.15.96=py36h516909a_0
86 | - scipy=1.2.1=py36h7c811a0_0
87 | - setuptools=41.0.1=py36_0
88 | - sip=4.19.8=py36hf484d3e_0
89 | - six=1.12.0=py36_0
90 | - sqlite=3.28.0=h7b6447c_0
91 | - tensorboard=1.9.0=py36hf484d3e_0
92 | - tensorflow=1.9.0=gpu_py36h02c5d5e_1
93 | - tensorflow-base=1.9.0=gpu_py36h6ecc378_0
94 | - tensorflow-estimator=1.13.0=py_0
95 | - tensorflow-gpu=1.9.0=hf154084_0
96 | - termcolor=1.1.0=py36_1
97 | - tk=8.6.8=hbc83047_0
98 | - tornado=6.0.2=py36h7b6447c_0
99 | - werkzeug=0.15.4=py_0
100 | - wheel=0.33.4=py36_0
101 | - xz=5.2.4=h14c3975_4
102 | - yaml=0.1.7=had09818_2
103 | - zlib=1.2.11=h7b6447c_3
104 | - zstd=1.3.7=h0b5b093_0
105 |
106 |
107 |
--------------------------------------------------------------------------------
/networks/classifiers.py:
--------------------------------------------------------------------------------
1 | from math import ceil
2 |
3 | from keras.layers.merge import Concatenate, Add
4 | from keras.layers import AveragePooling2D, ZeroPadding2D
5 |
6 | from keras.layers import Activation
7 | from keras.layers import Conv2D
8 | from keras.layers import Layer
9 |
10 | from networks import resnet
11 | import keras.backend as K
12 | from keras.backend import tf as ktf
13 |
14 |
15 | class Upsampling(Layer):
16 |
17 | def __init__(self, new_size, **kwargs):
18 | self.new_size = new_size
19 | super(Upsampling, self).__init__(**kwargs)
20 |
21 | def build(self, input_shape):
22 | super(Upsampling, self).build(input_shape)
23 |
24 | def call(self, inputs, **kwargs):
25 | new_height, new_width = self.new_size
26 | resized = ktf.image.resize_images(inputs, [new_height, new_width],
27 | align_corners=True)
28 | return resized
29 |
30 | def compute_output_shape(self, input_shape):
31 | return tuple([None, self.new_size[0], self.new_size[1], input_shape[3]])
32 |
33 | def get_config(self):
34 | config = super(Upsampling, self).get_config()
35 | config['new_size'] = self.new_size
36 | return config
37 |
38 |
39 | def psp_block(prev_layer, level, feature_map_shape, input_shape):
40 | if input_shape == (512, 512):
41 | kernel_strides_map = {1: [64, 64],
42 | 2: [32, 32],
43 | 3: [22, 21],
44 | 6: [11, 9]} # TODO: Level 6: Kernel correct, but stride not exactly the same as Pytorch
45 | else:
46 | raise ValueError("Pooling parameters for input shape " + input_shape + " are not defined.")
47 |
48 | if K.image_data_format() == 'channels_last':
49 | bn_axis = 3
50 | else:
51 | bn_axis = 1
52 |
53 | names = [
54 | "class_psp_" + str(level) + "_conv",
55 | "class_psp_" + str(level) + "_bn"
56 | ]
57 | kernel = (kernel_strides_map[level][0], kernel_strides_map[level][0])
58 | strides = (kernel_strides_map[level][1], kernel_strides_map[level][1])
59 | prev_layer = AveragePooling2D(kernel, strides=strides)(prev_layer)
60 | prev_layer = Conv2D(512, (1, 1), strides=(1, 1), name=names[0], use_bias=False)(prev_layer)
61 | prev_layer = resnet.BN(bn_axis, name=names[1])(prev_layer)
62 | prev_layer = Activation('relu')(prev_layer)
63 | prev_layer = Upsampling(feature_map_shape)(prev_layer)
64 | return prev_layer
65 |
66 |
67 | def build_pyramid_pooling_module(res, input_shape, nb_classes, sigmoid=False, output_size=None):
68 | """Build the Pyramid Pooling Module."""
69 | # ---PSPNet concat layers with Interpolation
70 | feature_map_size = tuple(int(ceil(input_dim / 8.0)) for input_dim in input_shape)
71 | if K.image_data_format() == 'channels_last':
72 | bn_axis = 3
73 | else:
74 | bn_axis = 1
75 | print("PSP module will interpolate to a final feature map size of %s" %
76 | (feature_map_size, ))
77 |
78 | interp_block1 = psp_block(res, 1, feature_map_size, input_shape)
79 | interp_block2 = psp_block(res, 2, feature_map_size, input_shape)
80 | interp_block3 = psp_block(res, 3, feature_map_size, input_shape)
81 | interp_block6 = psp_block(res, 6, feature_map_size, input_shape)
82 |
83 | # concat all these layers. resulted
84 | res = Concatenate()([interp_block1,
85 | interp_block2,
86 | interp_block3,
87 | interp_block6,
88 | res])
89 | x = Conv2D(512, (1, 1), strides=(1, 1), padding="same", name="class_psp_reduce_conv", use_bias=False)(res)
90 | x = resnet.BN(bn_axis, name="class_psp_reduce_bn")(x)
91 | x = Activation('relu')(x)
92 |
93 | x = Conv2D(nb_classes, (1, 1), strides=(1, 1), name="class_psp_final_conv")(x)
94 |
95 | if output_size:
96 | x = Upsampling(output_size)(x)
97 |
98 | if sigmoid:
99 | x = Activation('sigmoid')(x)
100 | return x
101 |
--------------------------------------------------------------------------------
/networks/dextr.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | from os.path import splitext, join
3 | import numpy as np
4 | from scipy import misc
5 | from keras import backend as K
6 |
7 | import tensorflow as tf
8 | from networks import resnet
9 |
10 | from mypath import Path
11 |
12 |
13 | class DEXTR(object):
14 | """Pyramid Scene Parsing Network by Hengshuang Zhao et al 2017"""
15 |
16 | def __init__(self, nb_classes, resnet_layers, input_shape, weights, num_input_channels=4,
17 | classifier='psp', use_numpy=False, sigmoid=False):
18 | self.input_shape = input_shape
19 | self.num_input_channels = num_input_channels
20 | self.sigmoid = sigmoid
21 | self.model = resnet.build_network(nb_classes=nb_classes, resnet_layers=resnet_layers, num_input_channels=num_input_channels,
22 | input_shape=self.input_shape, classifier=classifier, sigmoid=self.sigmoid, output_size=self.input_shape)
23 | if use_numpy:
24 | print("No Keras model & weights found, import from npy weights.")
25 | self.set_npy_weights(weights)
26 | else:
27 | print("Loading weights from H5 file.")
28 | h5_path = join(Path.models_dir(), weights + '.h5')
29 | self.model.load_weights(h5_path)
30 |
31 | def predict(self, img):
32 | # Preprocess
33 | img = misc.imresize(img, self.input_shape)
34 | img = img.astype('float32')
35 | probs = self.feed_forward(img)
36 | return probs
37 |
38 | def feed_forward(self, data):
39 | print("Predicting...")
40 | assert data.shape == (self.input_shape[0], self.input_shape[1], self.num_input_channels)
41 | prediction = self.model.predict(np.expand_dims(data, 0))[0]
42 | print("Finished prediction...")
43 | return prediction
44 |
45 | def set_npy_weights(self, weights_path):
46 | npy_weights_path = join("weights", "npy", weights_path + ".npy")
47 | h5_path = join(Path.models_dir(), weights_path + '.h5')
48 | # h5_path_model = join("models", weights_path + ".h5")
49 |
50 | print("Importing weights from %s" % npy_weights_path)
51 | weights = np.load(npy_weights_path, encoding='bytes').item()
52 | for layer in self.model.layers:
53 | # print('{}'.format(layer.name))
54 | if layer.name[:2] == 'bn' or layer.name[-2:] == 'bn':
55 | print('{}'.format(layer.name))
56 | # print('{} {}'.format(layer.name, layer.get_weights()[0].shape))
57 | gamma = weights[layer.name]['gamma']
58 | beta = weights[layer.name]['beta']
59 | moving_mean = weights[layer.name]['moving_mean']
60 | moving_variance = weights[layer.name]['moving_variance']
61 |
62 | self.model.get_layer(layer.name).set_weights([gamma, beta, moving_mean, moving_variance])
63 |
64 | elif layer.name[:3] == 'res' or layer.name[-4:] == 'conv' or layer.name[:4] == 'conv':
65 | print('{}'.format(layer.name))
66 | # print('{} {}'.format(layer.name, layer.get_weights()[0].shape))
67 | if len(self.model.get_layer(layer.name).get_weights()) == 2:
68 | weight = weights[layer.name]['weights']
69 | biases = weights[layer.name]['biases']
70 | if biases is None:
71 | raise ValueError('Bias inconsistency')
72 | self.model.get_layer(layer.name).set_weights([weight, biases])
73 | else:
74 | weight = weights[layer.name]['weights']
75 | self.model.get_layer(layer.name).set_weights([weight])
76 |
77 | print('Finished importing weights.')
78 |
79 | print("Writing keras weights")
80 | self.model.save_weights(h5_path)
81 | # models.save_model(self.model, h5_path_model, include_optimizer=False)
82 |
83 | print("Finished writing Keras model & weights")
84 |
85 |
86 | if __name__ == "__main__":
87 | classifier = 'psp'
88 | input_size = 512
89 | num_input_channels = 4
90 | resnet_size = 101
91 | image = 'ims/dog_512.png'
92 | extreme_points = 'ims/dog_512_extreme.png'
93 |
94 | input_type = 'bbox' if num_input_channels == 3 else 'extreme'
95 |
96 | model = 'dextr_pascal-sbd'
97 |
98 | # Handle input and output args
99 | sess = tf.Session()
100 | K.set_session(sess)
101 |
102 | with sess.as_default():
103 | dextr = DEXTR(nb_classes=1, resnet_layers=resnet_size, input_shape=(input_size, input_size), weights=model,
104 | num_input_channels=num_input_channels, classifier=classifier, use_numpy=False, sigmoid=True)
105 |
106 | img = misc.imread(image, mode='RGB')
107 | if num_input_channels == 4:
108 | extreme = misc.imread(extreme_points)
109 |
110 | img_extreme = np.zeros((input_size, input_size, 4))
111 | img_extreme[:, :, :3] = img
112 | img_extreme[:, :, 3] = extreme
113 | img_extreme = np.expand_dims(img_extreme.astype('float32'), 0)
114 | else:
115 | img_extreme = np.expand_dims(img.astype('float32'), 0)
116 |
117 | pred = dextr.model.predict(img_extreme)[0, :, :, 0]
118 |
119 | mask = pred > 0.8
120 |
121 | filename, ext = splitext(image)
122 |
123 | misc.imsave(filename + "_seg_"+ classifier + ext, mask.astype(np.uint8)*255)
124 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Deep Extreme Cut (DEXTR) based Annotation Tool
2 | is a simple matplotlib-based annotation User Interface (UI) that can be used for extracting segmentation masks for images. The main advantage of using this tool is the speed of annotation, as even for complex objects (e.g. the animals in the following image) the segmentation masks can be acquired by annotating only the four extreme points (left, right, top and bottom) for that object.
3 |
4 |

5 |
6 | This repository builds on the original work of [scaelles/DEXTR-KerasTensorflowPyTorch](https://github.com/scaelles/DEXTR-KerasTensorflow) by providing extra code that extends their demo code into a simple and elegant UI for annotating segmentation masks. The tool can be invoked from the command line and offers tracking of annotation progress between subsequent runs (i.e., for a given source images folder, it can track which images are already annotated, not annotated or skipped). The resulting segmentation masks can be saved either as *png* or as *numpy* array (.npy) files.
7 |
8 |
9 | ## Deep Extreme Cut (DEXTR)
10 | The `DEXTR` code used in this fork is a Keras+TensorFlow based re-implementation of original [PyTorch](https://github.com/scaelles/DEXTR-PyTorch) code by the same authors. More information on `DEXTR` can be found on the associated [project page](http://www.vision.ee.ethz.ch/~cvlsegmentation/dextr). A short summary is presented as follows:
11 |
12 | 
13 |
14 | #### Summary
15 | `DEXTR` is a deep-learning based approach to obtain precise object segmentation in images and videos. To achieve the same, it follows a semiautomatic approach where (usually) user-defined object extreme points are added as an extra channel to an image before it is input into a Convolutional Neural Network (CNN). The CNN learns to transform this information into a segmentation of an object that matches those extreme points. This approach is thus highly useful for guided segmentation (grabcut-style), interactive segmentation, video object segmentation, and dense segmentation annotation.
16 |
17 |
18 | ## Annotation Tool
19 | The annotation tool is a simple but powerful matplotlib-based UI that allows users to easily and interactively annotate images to obtain object segmentation masks for the same. Some of the main features of this tool are as follows:
20 | - easy modification of settings using a YAML-based configuration file.
21 | - ability to annotate extreme points for multiple objects in a image.
22 | - visualisation of results for each object during annotation.
23 | - ability to redo annotation if object results are not correct or if wrong points were selected.
24 | - ability to skip annotation if object results are unsatisfactory/wrong.
25 | - multiple images can be annotated in a session.
26 | - progress tracking across sessions. Thus, skipped or already annotated images are not shown during subsequent runs.
27 |
28 | More details on the different settings and using the annotation tool are provided in the later sections.
29 |
30 |
31 | ## Setup
32 | It is good practice to work with virtual environments when trying out new code. So please setup a virtual environment using either Python directly or *anaconda*, as you prefer. The code here was developed and tested using [Anaconda](https://docs.anaconda.com/anaconda/) with Python version 3.6, so we suggest you to do the same. The simplest way to get started is to follow the instructions below.
33 |
34 | 0. Clone this repo:
35 | ```Shell
36 | git clone https://github.com/karan-shr/DEXTR-AnnoTool
37 | cd DEXTR-AnnoTool
38 | ```
39 |
40 | 1. Setting up the environment:
41 | ```Shell
42 | conda env create -n dextr_annotool -f conda_env.yml
43 | ```
44 | Where `dextr_annotool` is the name of the environment (change if required) and `conda_env.yml` is the accompanying *conda* environment file. If you are using *pip* or installing packages manually, pay special attention to the package versions.
45 |
46 | 2. Download the model by running the script inside ```models/```:
47 | ```Shell
48 | cd models/
49 | chmod +x download_dextr_model.sh
50 | ./download_dextr_model.sh
51 | cd ..
52 | ```
53 | The default model is trained on PASCAL VOC Segmentation train + SBD (10582 images). To download models trained on PASCAL VOC Segmentation train or COCO, please visit the [project page](http://www.vision.ee.ethz.ch/~cvlsegmentation/dextr/#downloads). You can also manually download the models and place them in the models directory.
54 |
55 | 3. To demo the annotation UI using the provided sample images, please run:
56 | ```Shell
57 | python annotate.py -c anno_cfg.yml
58 | ```
59 | If you have multiple GPUs, you can specify which one should be used (for example gpu with id 0):
60 | ```Shell
61 | CUDA_VISIBLE_DEVICES=0 python annotate.py -c anno_cfg.yml
62 | ```
63 |
64 |
65 | ## Usage
66 |
67 | To get started annotating your dataset,
68 |
69 | 1. Modify the `anno_cfg.yml` configuration file: The comments in this file explain the purpose of the various setting parameters that the user can modify. Nevertheless, a brief description of the parameters whose purpose might not be clear at first sight is as follows:
70 | * `update` - when the program runs the first time it creates an annotation progress tracking file (more on this later) by scanning the source folder for all *png* and *jpeg* files and adding them to this file. The `update` parameter allows the user to specify if they would like to update the filenames cache every time the program runs. There are advantages to both approaches e.g., if the user added new data to the source folder but wants the annotation tool to only show the preexisting files, she can do so by setting `update: false`.
71 | * `admin` settings - typically the user shouldn't have to change these settings. Here the `progress_file: .anno_prog` is just the name for the annotation progress tracking file and `reset_progress: false` allows you to wipe the progress tracking history by making a new progress tracking file.
72 |
73 | 2. Once you have modified the `anno_cfg.yml` file to your liking, just undertake step 3 of the previous section to start annotating your data. Enjoy :thumbsup:
74 |
75 | Lastly, if you encounter any problems please open an issue.
76 |
77 |
78 | ## More information related to DEXTR
79 |
80 | ### Pre-trained models for DEXTR
81 | We provide the following DEXTR models, pre-trained on:
82 | * [PASCAL + SBD](https://data.vision.ee.ethz.ch/csergi/share/DEXTR/dextr_pascal-sbd.h5), trained on PASCAL VOC Segmentation train + SBD (10582 images). Achieves mIoU of 91.5% on PASCAL VOC Segmentation val.
83 | * [PASCAL](https://data.vision.ee.ethz.ch/csergi/share/DEXTR/dextr_pascal.h5), trained on PASCAL VOC Segmentation train (1464 images). Achieves mIoU of 90.5% on PASCAL VOC Segmentation val.
84 | * [COCO](https://data.vision.ee.ethz.ch/csergi/share/DEXTR/dextr_coco.h5), trained on COCO train 2014 (82783 images). Achieves mIoU of 87.8% on PASCAL VOC Segmentation val.
85 |
86 | ### Citation
87 | This annotation tool wouldn't have been possible without the excellent work on DEXTR by the team at ETH-Zurich. Please consider citing their following work if you use this tool:
88 |
89 | @Inproceedings{Man+18,
90 | Title = {Deep Extreme Cut: From Extreme Points to Object Segmentation},
91 | Author = {K.K. Maninis and S. Caelles and J. Pont-Tuset and L. {Van Gool}},
92 | Booktitle = {Computer Vision and Pattern Recognition (CVPR)},
93 | Year = {2018}
94 | }
95 |
96 | @InProceedings{Pap+17,
97 | Title = {Extreme clicking for efficient object annotation},
98 | Author = {D.P. Papadopoulos and J. Uijlings and F. Keller and V. Ferrari},
99 | Booktitle = {ICCV},
100 | Year = {2017}
101 | }
102 |
103 |
104 |
--------------------------------------------------------------------------------
/networks/resnet.py:
--------------------------------------------------------------------------------
1 | from keras.layers import Input
2 | from keras import layers
3 | from keras.layers import Activation
4 | from keras.layers import Conv2D
5 | from keras.layers import MaxPooling2D
6 | from keras.layers import ZeroPadding2D
7 | from keras.layers import BatchNormalization
8 | from keras.models import Model
9 |
10 | import keras.backend as K
11 |
12 | from networks.classifiers import build_pyramid_pooling_module
13 |
14 |
15 | def BN(axis, name=""):
16 | return BatchNormalization(axis=axis, momentum=0.1, name=name, epsilon=1e-5)
17 |
18 |
19 | def identity_block(input_tensor, kernel_size, filters, stage, block, dilation=1):
20 | """The identity block is the block that has no conv layer at shortcut.
21 |
22 | # Arguments
23 | input_tensor: input tensor
24 | kernel_size: defualt 3, the kernel size of middle conv layer at main path
25 | filters: list of integers, the filterss of 3 conv layer at main path
26 | stage: integer, current stage label, used for generating layer names
27 | block: 'a','b'..., current block label, used for generating layer names
28 | dilation: dilation of the intermediate convolution
29 |
30 | # Returns
31 | Output tensor for the block.
32 | """
33 | filters1, filters2, filters3 = filters
34 | if K.image_data_format() == 'channels_last':
35 | bn_axis = 3
36 | else:
37 | bn_axis = 1
38 | conv_name_base = 'res' + str(stage) + block + '_branch'
39 | bn_name_base = 'bn' + str(stage) + block + '_branch'
40 |
41 | x = Conv2D(filters1, (1, 1), name=conv_name_base + '2a', use_bias=False)(input_tensor)
42 | x = BN(axis=bn_axis, name=bn_name_base + '2a')(x)
43 | x = Activation('relu')(x)
44 |
45 | x = Conv2D(filters2, kernel_size, padding='same', name=conv_name_base + '2b', use_bias=False, dilation_rate=dilation)(x)
46 | x = BN(axis=bn_axis, name=bn_name_base + '2b')(x)
47 | x = Activation('relu')(x)
48 |
49 | x = Conv2D(filters3, (1, 1), name=conv_name_base + '2c', use_bias=False)(x)
50 | x = BN(axis=bn_axis, name=bn_name_base + '2c')(x)
51 |
52 | x = layers.add([x, input_tensor])
53 | x = Activation('relu')(x)
54 | return x
55 |
56 |
57 | def conv_block(input_tensor, kernel_size, filters, stage, block, strides=(1, 1), dilation=1):
58 | """conv_block is the block that has a conv layer at shortcut
59 |
60 | # Arguments
61 | input_tensor: input tensor
62 | kernel_size: defualt 3, the kernel size of middle conv layer at main path
63 | filters: list of integers, the filterss of 3 conv layer at main path
64 | stage: integer, current stage label, used for generating layer names
65 | block: 'a','b'..., current block label, used for generating layer names
66 |
67 | # Returns
68 | Output tensor for the block.
69 |
70 | Note that from stage 3, the first conv layer at main path is with strides=(2,2)
71 | And the shortcut should have strides=(2,2) as well
72 | """
73 | filters1, filters2, filters3 = filters
74 | if K.image_data_format() == 'channels_last':
75 | bn_axis = 3
76 | else:
77 | bn_axis = 1
78 | conv_name_base = 'res' + str(stage) + block + '_branch'
79 | bn_name_base = 'bn' + str(stage) + block + '_branch'
80 |
81 | x = Conv2D(filters1, (1, 1), strides=strides, name=conv_name_base + '2a', use_bias=False)(input_tensor)
82 | x = BN(axis=bn_axis, name=bn_name_base + '2a')(x)
83 | x = Activation('relu')(x)
84 |
85 | x = Conv2D(filters2, kernel_size, padding='same', name=conv_name_base + '2b', use_bias=False, dilation_rate=dilation)(x)
86 | x = BN(axis=bn_axis, name=bn_name_base + '2b')(x)
87 | x = Activation('relu')(x)
88 |
89 | x = Conv2D(filters3, (1, 1), name=conv_name_base + '2c', use_bias=False)(x)
90 | x = BN(axis=bn_axis, name=bn_name_base + '2c')(x)
91 |
92 | shortcut = Conv2D(filters3, (1, 1), strides=strides, name=conv_name_base + '1', use_bias=False)(input_tensor)
93 | shortcut = BN(axis=bn_axis, name=bn_name_base + '1')(shortcut)
94 |
95 | x = layers.add([x, shortcut])
96 | x = Activation('relu')(x)
97 | return x
98 |
99 |
100 | def ResNet101(input_tensor=None):
101 |
102 | img_input = input_tensor
103 | if K.image_data_format() == 'channels_last':
104 | bn_axis = 3
105 | else:
106 | bn_axis = 1
107 |
108 | x = ZeroPadding2D((3, 3))(img_input)
109 | x = Conv2D(64, (7, 7), strides=(2, 2), name='conv1', use_bias=False)(x)
110 | x = BN(axis=bn_axis, name='bn_conv1')(x)
111 | x = Activation('relu')(x)
112 | x = ZeroPadding2D((1, 1))(x)
113 | x = MaxPooling2D((3, 3), strides=(2, 2), padding='valid')(x)
114 |
115 | x = conv_block(x, 3, [64, 64, 256], stage=2, block='a')
116 | x = identity_block(x, 3, [64, 64, 256], stage=2, block='b')
117 | x = identity_block(x, 3, [64, 64, 256], stage=2, block='c')
118 |
119 | x = conv_block(x, 3, [128, 128, 512], stage=3, block='a', strides=(2, 2))
120 | x = identity_block(x, 3, [128, 128, 512], stage=3, block='b')
121 | x = identity_block(x, 3, [128, 128, 512], stage=3, block='c')
122 | x = identity_block(x, 3, [128, 128, 512], stage=3, block='d')
123 |
124 | x = conv_block(x, 3, [256, 256, 1024], stage=4, block='a', dilation=2)
125 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='b', dilation=2)
126 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='c', dilation=2)
127 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='d', dilation=2)
128 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='e', dilation=2)
129 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='f', dilation=2)
130 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='g', dilation=2)
131 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='h', dilation=2)
132 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='i', dilation=2)
133 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='j', dilation=2)
134 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='k', dilation=2)
135 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='l', dilation=2)
136 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='m', dilation=2)
137 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='n', dilation=2)
138 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='o', dilation=2)
139 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='p', dilation=2)
140 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='q', dilation=2)
141 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='r', dilation=2)
142 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='s', dilation=2)
143 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='t', dilation=2)
144 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='u', dilation=2)
145 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='v', dilation=2)
146 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='w', dilation=2)
147 |
148 | x = conv_block(x, 3, [512, 512, 2048], stage=5, block='a', dilation=4)
149 | x = identity_block(x, 3, [512, 512, 2048], stage=5, block='b', dilation=4)
150 | x = identity_block(x, 3, [512, 512, 2048], stage=5, block='c', dilation=4)
151 |
152 | return x
153 |
154 |
155 | def build_network(nb_classes, input_shape, resnet_layers=101, classifier='psp', sigmoid=False, output_size=None,
156 | num_input_channels=4):
157 | """Build Network"""
158 | inp = Input((input_shape[0], input_shape[1], num_input_channels))
159 | if resnet_layers == 101:
160 | res = ResNet101(inp)
161 | else:
162 | ValueError('Resnet {} does not exist'.format(resnet_layers))
163 | if classifier == 'psp':
164 | print("Building network based on ResNet %i and PSP module expecting inputs of shape %s predicting %i classes" % (
165 | resnet_layers, input_shape, nb_classes))
166 | x = build_pyramid_pooling_module(res, input_shape, nb_classes, sigmoid=sigmoid, output_size=output_size)
167 | else:
168 | raise ValueError('Classifier not implemented.')
169 | model = Model(inputs=inp, outputs=x)
170 |
171 | return model
172 |
--------------------------------------------------------------------------------
/helpers/helpers.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | import cv2
4 | import random
5 | import numpy as np
6 |
7 |
8 | def tens2image(im):
9 | if im.size()[0] == 1:
10 | tmp = np.squeeze(im.numpy(), axis=0)
11 | else:
12 | tmp = im.numpy()
13 | if tmp.ndim == 2:
14 | return tmp
15 | else:
16 | return tmp.transpose((1, 2, 0))
17 |
18 |
19 | def crop2fullmask(crop_mask, bbox, im=None, im_size=None, zero_pad=False, relax=0, mask_relax=True,
20 | interpolation=cv2.INTER_CUBIC, scikit=False):
21 | if scikit:
22 | from skimage.transform import resize as sk_resize
23 | assert(not(im is None and im_size is None)), 'You have to provide an image or the image size'
24 | if im is None:
25 | im_si = im_size
26 | else:
27 | im_si = im.shape
28 | # Borers of image
29 | bounds = (0, 0, im_si[1] - 1, im_si[0] - 1)
30 |
31 | # Valid bounding box locations as (x_min, y_min, x_max, y_max)
32 | bbox_valid = (max(bbox[0], bounds[0]),
33 | max(bbox[1], bounds[1]),
34 | min(bbox[2], bounds[2]),
35 | min(bbox[3], bounds[3]))
36 |
37 | # Bounding box of initial mask
38 | bbox_init = (bbox[0] + relax,
39 | bbox[1] + relax,
40 | bbox[2] - relax,
41 | bbox[3] - relax)
42 |
43 | if zero_pad:
44 | # Offsets for x and y
45 | offsets = (-bbox[0], -bbox[1])
46 | else:
47 | assert((bbox == bbox_valid).all())
48 | offsets = (-bbox_valid[0], -bbox_valid[1])
49 |
50 | # Simple per element addition in the tuple
51 | inds = tuple(map(sum, zip(bbox_valid, offsets + offsets)))
52 |
53 | if scikit:
54 | crop_mask = sk_resize(crop_mask, (bbox[3] - bbox[1] + 1, bbox[2] - bbox[0] + 1), order=0, mode='constant').astype(crop_mask.dtype)
55 | else:
56 | crop_mask = cv2.resize(crop_mask, (bbox[2] - bbox[0] + 1, bbox[3] - bbox[1] + 1), interpolation=interpolation)
57 | result_ = np.zeros(im_si)
58 | result_[bbox_valid[1]:bbox_valid[3] + 1, bbox_valid[0]:bbox_valid[2] + 1] = \
59 | crop_mask[inds[1]:inds[3] + 1, inds[0]:inds[2] + 1]
60 |
61 | result = np.zeros(im_si)
62 | if mask_relax:
63 | result[bbox_init[1]:bbox_init[3]+1, bbox_init[0]:bbox_init[2]+1] = \
64 | result_[bbox_init[1]:bbox_init[3]+1, bbox_init[0]:bbox_init[2]+1]
65 | else:
66 | result = result_
67 |
68 | return result
69 |
70 |
71 | def overlay_mask(im, ma, colors=None, alpha=0.5):
72 | assert np.max(im) <= 1.0
73 | if colors is None:
74 | colors = np.load(os.path.join(os.path.dirname(__file__), 'pascal_map.npy'))/255.
75 | else:
76 | colors = np.append([[0.,0.,0.]], colors, axis=0);
77 |
78 | if ma.ndim == 3:
79 | assert len(colors) >= ma.shape[0], 'Not enough colors'
80 | ma = ma.astype(np.bool)
81 | im = im.astype(np.float32)
82 |
83 | if ma.ndim == 2:
84 | fg = im * alpha+np.ones(im.shape) * (1 - alpha) * colors[1, :3] # np.array([0,0,255])/255.0
85 | else:
86 | fg = []
87 | for n in range(ma.ndim):
88 | fg.append(im * alpha + np.ones(im.shape) * (1 - alpha) * colors[1+n, :3])
89 | # Whiten background
90 | bg = im.copy()
91 | if ma.ndim == 2:
92 | bg[ma == 0] = im[ma == 0]
93 | bg[ma == 1] = fg[ma == 1]
94 | total_ma = ma
95 | else:
96 | total_ma = np.zeros([ma.shape[1], ma.shape[2]])
97 | for n in range(ma.shape[0]):
98 | tmp_ma = ma[n, :, :]
99 | total_ma = np.logical_or(tmp_ma, total_ma)
100 | tmp_fg = fg[n]
101 | bg[tmp_ma == 1] = tmp_fg[tmp_ma == 1]
102 | bg[total_ma == 0] = im[total_ma == 0]
103 |
104 | # [-2:] is s trick to be compatible both with opencv 2 and 3
105 | contours = cv2.findContours(total_ma.copy().astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2:]
106 | cv2.drawContours(bg, contours[0], -1, (0.0, 0.0, 0.0), 1)
107 |
108 | return bg
109 |
110 |
111 | def overlay_masks(im, masks, alpha=0.5):
112 | colors = np.load(os.path.join(os.path.dirname(__file__), 'pascal_map.npy'))/255.
113 |
114 | if isinstance(masks, np.ndarray):
115 | masks = [masks]
116 |
117 | assert len(colors) >= len(masks), 'Not enough colors'
118 |
119 | ov = im.copy()
120 | im = im.astype(np.float32)
121 | total_ma = np.zeros([im.shape[0], im.shape[1]])
122 | i = 1
123 | for ma in masks:
124 | ma = ma.astype(np.bool)
125 | fg = im * alpha+np.ones(im.shape) * (1 - alpha) * colors[i, :3] # np.array([0,0,255])/255.0
126 | i = i + 1
127 | ov[ma == 1] = fg[ma == 1]
128 | total_ma += ma
129 |
130 | # [-2:] is s trick to be compatible both with opencv 2 and 3
131 | contours = cv2.findContours(ma.copy().astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2:]
132 | cv2.drawContours(ov, contours[0], -1, (0.0, 0.0, 0.0), 1)
133 | ov[total_ma == 0] = im[total_ma == 0]
134 |
135 | return ov
136 |
137 |
138 | def extreme_points(mask, pert):
139 | def find_point(id_x, id_y, ids):
140 | sel_id = ids[0][random.randint(0, len(ids[0]) - 1)]
141 | return [id_x[sel_id], id_y[sel_id]]
142 |
143 | # List of coordinates of the mask
144 | inds_y, inds_x = np.where(mask > 0.5)
145 |
146 | # Find extreme points
147 | return np.array([find_point(inds_x, inds_y, np.where(inds_x <= np.min(inds_x)+pert)), # left
148 | find_point(inds_x, inds_y, np.where(inds_x >= np.max(inds_x)-pert)), # right
149 | find_point(inds_x, inds_y, np.where(inds_y <= np.min(inds_y)+pert)), # top
150 | find_point(inds_x, inds_y, np.where(inds_y >= np.max(inds_y)-pert)) # bottom
151 | ])
152 |
153 |
154 | def get_bbox(mask, points=None, pad=0, zero_pad=False):
155 | if points is not None:
156 | inds = np.flip(points.transpose(), axis=0)
157 | else:
158 | inds = np.where(mask > 0)
159 |
160 | if inds[0].shape[0] == 0:
161 | return None
162 |
163 | if zero_pad:
164 | x_min_bound = -np.inf
165 | y_min_bound = -np.inf
166 | x_max_bound = np.inf
167 | y_max_bound = np.inf
168 | else:
169 | x_min_bound = 0
170 | y_min_bound = 0
171 | x_max_bound = mask.shape[1] - 1
172 | y_max_bound = mask.shape[0] - 1
173 |
174 | x_min = max(inds[1].min() - pad, x_min_bound)
175 | y_min = max(inds[0].min() - pad, y_min_bound)
176 | x_max = min(inds[1].max() + pad, x_max_bound)
177 | y_max = min(inds[0].max() + pad, y_max_bound)
178 |
179 | return x_min, y_min, x_max, y_max
180 |
181 |
182 | def crop_from_bbox(img, bbox, zero_pad=False):
183 | # Borders of image
184 | bounds = (0, 0, img.shape[1] - 1, img.shape[0] - 1)
185 |
186 | # Valid bounding box locations as (x_min, y_min, x_max, y_max)
187 | bbox_valid = (max(bbox[0], bounds[0]),
188 | max(bbox[1], bounds[1]),
189 | min(bbox[2], bounds[2]),
190 | min(bbox[3], bounds[3]))
191 |
192 | if zero_pad:
193 | # Initialize crop size (first 2 dimensions)
194 | crop = np.zeros((bbox[3] - bbox[1] + 1, bbox[2] - bbox[0] + 1), dtype=img.dtype)
195 |
196 | # Offsets for x and y
197 | offsets = (-bbox[0], -bbox[1])
198 |
199 | else:
200 | assert(bbox == bbox_valid)
201 | crop = np.zeros((bbox_valid[3] - bbox_valid[1] + 1, bbox_valid[2] - bbox_valid[0] + 1), dtype=img.dtype)
202 | offsets = (-bbox_valid[0], -bbox_valid[1])
203 |
204 | # Simple per element addition in the tuple
205 | inds = tuple(map(sum, zip(bbox_valid, offsets + offsets)))
206 |
207 | img = np.squeeze(img)
208 | if img.ndim == 2:
209 | crop[inds[1]:inds[3] + 1, inds[0]:inds[2] + 1] = \
210 | img[bbox_valid[1]:bbox_valid[3] + 1, bbox_valid[0]:bbox_valid[2] + 1]
211 | else:
212 | crop = np.tile(crop[:, :, np.newaxis], [1, 1, 3]) # Add 3 RGB Channels
213 | crop[inds[1]:inds[3] + 1, inds[0]:inds[2] + 1, :] = \
214 | img[bbox_valid[1]:bbox_valid[3] + 1, bbox_valid[0]:bbox_valid[2] + 1, :]
215 |
216 | return crop
217 |
218 |
219 | def fixed_resize(sample, resolution, flagval=None):
220 |
221 | if flagval is None:
222 | if ((sample == 0) | (sample == 1)).all():
223 | flagval = cv2.INTER_NEAREST
224 | else:
225 | flagval = cv2.INTER_CUBIC
226 |
227 | if isinstance(resolution, int):
228 | tmp = [resolution, resolution]
229 | tmp[np.argmax(sample.shape[:2])] = int(round(float(resolution)/np.min(sample.shape[:2])*np.max(sample.shape[:2])))
230 | resolution = tuple(tmp)
231 |
232 | if sample.ndim == 2 or (sample.ndim == 3 and sample.shape[2] == 3):
233 | sample = cv2.resize(sample, resolution[::-1], interpolation=flagval)
234 | else:
235 | tmp = sample
236 | sample = np.zeros(np.append(resolution, tmp.shape[2]), dtype=np.float32)
237 | for ii in range(sample.shape[2]):
238 | sample[:, :, ii] = cv2.resize(tmp[:, :, ii], resolution[::-1], interpolation=flagval)
239 | return sample
240 |
241 |
242 | def crop_from_mask(img, mask, relax=0, zero_pad=False):
243 | if mask.shape[:2] != img.shape[:2]:
244 | mask = cv2.resize(mask, dsize=tuple(reversed(img.shape[:2])), interpolation=cv2.INTER_NEAREST)
245 |
246 | assert(mask.shape[:2] == img.shape[:2])
247 |
248 | bbox = get_bbox(mask, pad=relax, zero_pad=zero_pad)
249 |
250 | if bbox is None:
251 | return None
252 |
253 | crop = crop_from_bbox(img, bbox, zero_pad)
254 |
255 | return crop
256 |
257 |
258 | def make_gaussian(size, sigma=10, center=None, d_type=np.float64):
259 | """ Make a square gaussian kernel.
260 | size: is the dimensions of the output gaussian
261 | sigma: is full-width-half-maximum, which
262 | can be thought of as an effective radius.
263 | """
264 |
265 | x = np.arange(0, size[1], 1, float)
266 | y = np.arange(0, size[0], 1, float)
267 | y = y[:, np.newaxis]
268 |
269 | if center is None:
270 | x0 = y0 = size[0] // 2
271 | else:
272 | x0 = center[0]
273 | y0 = center[1]
274 |
275 | return np.exp(-4 * np.log(2) * ((x - x0) ** 2 + (y - y0) ** 2) / sigma ** 2).astype(d_type)
276 |
277 |
278 | def make_gt(img, labels, sigma=10, one_mask_per_point=False):
279 | """ Make the ground-truth for landmark.
280 | img: the original color image
281 | labels: label with the Gaussian center(s) [[x0, y0],[x1, y1],...]
282 | sigma: sigma of the Gaussian.
283 | one_mask_per_point: masks for each point in different channels?
284 | """
285 | h, w = img.shape[:2]
286 | if labels is None:
287 | gt = make_gaussian((h, w), center=(h//2, w//2), sigma=sigma)
288 | else:
289 | labels = np.array(labels)
290 | if labels.ndim == 1:
291 | labels = labels[np.newaxis]
292 | if one_mask_per_point:
293 | gt = np.zeros(shape=(h, w, labels.shape[0]))
294 | for ii in range(labels.shape[0]):
295 | gt[:, :, ii] = make_gaussian((h, w), center=labels[ii, :], sigma=sigma)
296 | else:
297 | gt = np.zeros(shape=(h, w), dtype=np.float64)
298 | for ii in range(labels.shape[0]):
299 | gt = np.maximum(gt, make_gaussian((h, w), center=labels[ii, :], sigma=sigma))
300 |
301 | gt = gt.astype(dtype=img.dtype)
302 |
303 | return gt
304 |
305 |
306 | def cstm_normalize(im, max_value):
307 | """
308 | Normalize image to range 0 - max_value
309 | """
310 | imn = max_value*(im - im.min()) / max((im.max() - im.min()), 1e-8)
311 | return imn
312 |
313 |
314 | def generate_param_report(logfile, param):
315 | log_file = open(logfile, 'w')
316 | for key, val in param.items():
317 | log_file.write(key+':'+str(val)+'\n')
318 | log_file.close()
319 |
--------------------------------------------------------------------------------
/helpers/annotools.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import io
3 | from ruamel.yaml import YAML
4 | import ruamel.yaml.util as ymlutil
5 | from os import path, makedirs, listdir
6 | import warnings
7 | from PIL import Image
8 | import numpy as np
9 |
10 |
11 | # configure ruamel.yaml
12 | yaml = YAML()
13 | yaml.default_flow_style = False
14 |
15 |
16 | # setup custom exception classes
17 | class ConfigFileWarning(UserWarning):
18 | pass
19 |
20 |
21 | class ConfigFileError(Exception):
22 | pass
23 |
24 |
25 | # ----------------------------------------General helper functions------------------------------------------------------
26 |
27 | def _query_yes_no(question, default="no"):
28 | """Ask a yes/no question via raw_input() and return their answer.
29 |
30 | "question" is a string that is presented to the user.
31 | "default" is the presumed answer if the user just hits .
32 | It must be "yes" (the default), "no" or None (meaning
33 | an answer is required of the user).
34 |
35 | The "answer" return value is True for "yes" or False for "no".
36 | """
37 | valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False}
38 | if default is None:
39 | prompt = " [y/n] "
40 | elif default == "yes":
41 | prompt = " [Y/n] "
42 | elif default == "no":
43 | prompt = " [y/N] "
44 | else:
45 | raise ValueError("invalid default answer: '%s'" % default)
46 |
47 | while True:
48 | sys.stdout.write(question + prompt)
49 | choice = input().lower()
50 | if default is not None and choice == '':
51 | return valid[default]
52 | elif choice in valid:
53 | return valid[choice]
54 | else:
55 | sys.stdout.write("Please respond with 'yes' or 'no' (or 'y' or 'n').\n")
56 |
57 |
58 | def _files_to_annotate(source):
59 | dir_contains = listdir(source)
60 | to_annotate = []
61 | for name in dir_contains:
62 | if name.endswith('.jpg') or name.endswith('.png'):
63 | to_annotate.append(name)
64 |
65 | return to_annotate
66 |
67 |
68 | # -------------------------------------Functions for progress tracking--------------------------------------------------
69 |
70 | def _update_filecache(config, filename):
71 | # parse file names already in the progress logging file
72 | with io.open(filename, 'r') as progress_file:
73 | _progress = yaml.load(progress_file)
74 |
75 | curr_files = list(_progress['annotated'])
76 | all_files = _files_to_annotate(config['required']['source'])
77 | # make new dict based on files not in currently listed files (curr_files)
78 | new_files = [f for f in all_files if f not in curr_files]
79 | new_files.sort() # sort the list
80 | tmp_extra_dict = {f: 'no' for f in new_files}
81 | # append this new dict to current dict
82 | _progress['annotated'].update(tmp_extra_dict)
83 |
84 | # write this to file
85 | with io.open(filename, 'w+') as progress_file:
86 | yaml.dump(_progress, progress_file)
87 |
88 |
89 | def _get_to_annotate(filename):
90 | # load progress file again and return list of keys (filenames) from annotated section
91 | with io.open(filename, 'r') as progfile:
92 | progress = yaml.load(progfile)
93 |
94 | files_anno = [] # to hold file names for files to be annotated
95 | for file, status in list(progress['annotated'].items()):
96 | if status.lower() == 'no':
97 | files_anno.append(file)
98 |
99 | return files_anno
100 |
101 |
102 | def _prog_update_done(config, source_filename):
103 |
104 | # open and edit the progress file
105 | progressfile_path = path.join(config['required']['source'], config['admin']['progress_file'])
106 |
107 | with io.open(progressfile_path, 'r') as progress_file:
108 | progress = yaml.load(progress_file)
109 |
110 | progress['annotated'][source_filename] = 'yes'
111 |
112 | # save update to progress file
113 | with io.open(progressfile_path, 'w+') as progress_file:
114 | yaml.dump(progress, progress_file)
115 |
116 |
117 | def prog_update_skip(config, source_filename):
118 |
119 | # open and edit the progress file
120 | progressfile_path = path.join(config['required']['source'], config['admin']['progress_file'])
121 |
122 | with io.open(progressfile_path, 'r') as progress_file:
123 | progress = yaml.load(progress_file)
124 |
125 | progress['annotated'][source_filename] = 'skip'
126 |
127 | # save update to progress file
128 | with io.open(progressfile_path, 'w+') as progress_file:
129 | yaml.dump(progress, progress_file)
130 |
131 |
132 | def _make_progfile(config, filename):
133 | # parse the folder and add filename to a dict
134 | files = _files_to_annotate(config['required']['source'])
135 | files.sort() # return sorted list
136 |
137 | if not files:
138 | raise ConfigFileError("No jpg or png files found in the source folder specified in the config file. Aborting "
139 | "creation of progress file and exiting...")
140 |
141 | # make a temporary dict to store file names and annotation status
142 | tmp_anno_dict = {f: 'no' for f in files}
143 | # make a temporary dict to get come info from the config file dict with the the same section headers
144 | tmp_info_dict = config['required']
145 |
146 | # join the dicts into common dict to be saved into the progress tracking file
147 | _progress = {'required': tmp_info_dict, 'annotated': tmp_anno_dict}
148 |
149 | with io.open(filename, 'w') as progfile:
150 | yaml.dump(_progress, progfile)
151 |
152 | print("Annotation progress tracking file created.\n\n"
153 | "********************************************************************************\n"
154 | "Tip: if the source directory changes (i.e. if files are added/removed), in config\n"
155 | "file set 'update: True' to update the file-names cache in the progress tracker.\n"
156 | "********************************************************************************")
157 |
158 |
159 | def config_prog_log(config, cfg_file):
160 |
161 | # progress file settings
162 | _progress_filename = path.join(config['required']['source'], config['admin']['progress_file'])
163 |
164 | # when progress file doesn't exist
165 | if not path.isfile(_progress_filename):
166 | # idiot check
167 | if config['admin']['reset_progress']:
168 | warnings.warn("You are resetting the progress file before it was setup. Ignoring 'reset: True' and setting"
169 | "'reset: False' in config file to prevent any errors later.", ConfigFileWarning)
170 | sys.stderr.flush() # to print warning immediately
171 | _modify_config(cfg_file, 'reset_progress', False)
172 | if config['optional']['update']:
173 | warnings.warn("You are updating the progress file before it was setup. Ignoring 'update: True' and"
174 | " continuing to make the progress file. If required, please change 'update:' status in the"
175 | " config file.", ConfigFileWarning)
176 | sys.stderr.flush() # to print warning immediately
177 |
178 | # prompt user that file will be created
179 | print("Progress file that tracks your annotation history doesn't exist. So:\n"
180 | "(1) either this is the first time you are annotating files in the provided source folder, or\n"
181 | "(2) you deleted the file. Please recover it if you want to continue from last annotated image.\n"
182 | "In either case, will try to create a new progress tracking file now...")
183 | _make_progfile(config, _progress_filename)
184 |
185 | # when progress file exists
186 | elif path.isfile(_progress_filename):
187 | # idiot check
188 | if config['admin']['reset_progress'] and config['optional']['update']:
189 | raise ConfigFileError("You've set 'reset: True' and 'update: True'. What do you want? If you want to...\n"
190 | "- reset annotation progress, then set 'reset: True' and 'update: False'.\n"
191 | "- update annotation progress file-cache, then set 'update: True' and 'reset: False'.\n"
192 | "Exiting now...")
193 | elif config['admin']['reset_progress']:
194 | reset_prompt = _query_yes_no("In config file 'reset: True'. Thus, you'll lose your annotation progress so "
195 | "far.\n Are you sure? Enter 'yes' to continue resetting or 'no' otherwise")
196 | if reset_prompt:
197 | print("Okay then. Remember you've been warned. Resetting...")
198 | _make_progfile(config, _progress_filename)
199 | elif not reset_prompt:
200 | print("Phew...be careful don't modify stuff you don't understand. Ignoring resetting...")
201 | elif config['optional']['update']:
202 | print("In config file 'update: True', so source folder will be scanned again and new files will be added to"
203 | " progress tracking cache.")
204 | _update_filecache(config, _progress_filename)
205 |
206 | # load config file again in case any modifications were made
207 | with io.open(cfg_file, 'r') as conffile:
208 | updated_config = yaml.load(conffile)
209 |
210 | to_annotate = _get_to_annotate(_progress_filename)
211 |
212 | return updated_config, to_annotate
213 |
214 |
215 | # -------------------------------------Configuration file operations----------------------------------------------------
216 |
217 | def _modify_config(cfg_file, param, param_new_value=False):
218 | # open file
219 | config, ind, bsi = ymlutil.load_yaml_guess_indent(open(cfg_file))
220 |
221 | if param is 'reset_progress':
222 | config['admin']['reset_progress'] = param_new_value
223 | elif param is 'update':
224 | config['optional']['update'] = param_new_value
225 |
226 | with io.open(cfg_file, 'w') as conffile:
227 | yaml.dump(config, conffile)
228 |
229 |
230 | def load_config(cfg_file):
231 |
232 | # load config from specified yaml file
233 | with io.open(cfg_file, 'r') as conffile:
234 | config = yaml.load(conffile)
235 |
236 | # source folder exists?
237 | if not path.exists(config['required']['source']):
238 | raise ConfigFileError("The source folder doesn't exist. Please properly set folder in config file. Exiting...")
239 |
240 | # destination folder exists? No, make it.
241 | if not path.exists(config['required']['destination']):
242 | warnings.warn("The specified destination folder for segmasks doesn't exist, making it.", ConfigFileWarning)
243 | sys.stderr.flush() # to print warning immediately
244 | makedirs(config['required']['destination'])
245 |
246 | return config
247 |
248 |
249 | # --------------------------------Functions for generating and saving mask images---------------------------------------
250 |
251 | def get_img_segmasks(im, masks):
252 | orig_img = im.copy()
253 | # not sure if this is required
254 | if isinstance(masks, np.ndarray):
255 | masks = [masks]
256 | # full image mask
257 | img_mask = np.zeros([im.shape[0], im.shape[1]]) # init full image mask with zeros
258 | for n_mask in range(len(masks)):
259 | curr_mask = masks[n_mask]
260 | img_mask[curr_mask] = n_mask + 1
261 |
262 | return img_mask
263 |
264 |
265 | def save_mask(mask_array, config, source_filename):
266 | # get the mask image name
267 | source_file_initial, _ = source_filename.split('.')
268 | mask_file_name = source_file_initial + config['optional']['mask_suffix']
269 |
270 | # make mask image from mask array and save it to disk
271 | mask_array_mod = mask_array.astype(np.uint8) # convert array to uint8 before saving
272 |
273 | if config['optional']['save_format'] != 'png' and config['optional']['save_format'] != 'npy':
274 | raise ConfigFileError("Mask save format can only be 'png' or 'npy'. Change setting in config file.")
275 | elif config['optional']['save_format'] == 'png':
276 | mask_img = Image.fromarray(mask_array_mod, mode='L') # mode L is for 8-bit pixels, black and white
277 | mask_name_full = mask_file_name + '.png'
278 | mask_save_path = path.join(config['required']['destination'], mask_name_full)
279 | mask_img.save(mask_save_path)
280 | elif config['optional']['save_format'] == 'npy':
281 | mask_save_path = path.join(config['required']['destination'], mask_file_name)
282 | np.save(mask_save_path, mask_array_mod)
283 |
284 | # now update the progress file
285 | _prog_update_done(config, source_filename)
286 |
287 | return mask_array_mod
288 |
--------------------------------------------------------------------------------
/annotate.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import argparse
4 | from os import path
5 |
6 | from PIL import Image
7 | import numpy as np
8 | from matplotlib import pyplot as plt
9 | from matplotlib.widgets import Button
10 |
11 | import tensorflow as tf
12 | from keras import backend as K
13 |
14 | # ---user-defined modules---
15 | # repo defined
16 | from networks.dextr import DEXTR
17 | from mypath import Path
18 | from helpers import helpers as helpers
19 | from helpers import annotools as tools
20 |
21 | modelName = 'dextr_pascal-sbd'
22 | pad = 50
23 | thres = 0.8
24 | gpu_id = 0
25 |
26 |
27 | if __name__ == "__main__":
28 |
29 | # parse command line arguments
30 | parser = argparse.ArgumentParser(description='annotation tool based on DEXTR for annotating segmentation masks for'
31 | ' images')
32 | required_arguments = parser.add_argument_group('Required arguments')
33 | required_arguments.add_argument('-c', '--config', type=str, help='path to the yaml file that holds the'
34 | ' configuration', required=True)
35 | args = parser.parse_args()
36 |
37 | # ---------------------------------Setting up based on yaml config--------------------------------------------------
38 |
39 | # load (and check) the user defined config
40 | cfg = tools.load_config(args.config)
41 | # setup progress file: check config to detect what should be done, return files that need to be annotated
42 | cfg, files_to_annotate = tools.config_prog_log(cfg, args.config)
43 |
44 | if not files_to_annotate:
45 | print("Yippie...finished annotating all files in the source folder. Exiting...")
46 | exit(0)
47 |
48 | # ------------------------------------Setup TensorFlow session------------------------------------------------------
49 | # Handle input and output args
50 | sess = tf.Session()
51 | K.set_session(sess)
52 |
53 | with sess.as_default():
54 | net = DEXTR(nb_classes=1, resnet_layers=101, input_shape=(512, 512), weights=modelName,
55 | num_input_channels=4, classifier='psp', sigmoid=True)
56 |
57 | # -----------------------------------Start annotation interface-------------------------------------------------
58 | _KEEPannotating = True # annotation status flag
59 |
60 | # Initialise the UI
61 | plt.switch_backend('TkAgg') # force 'TkAgg' backend
62 | ui = plt.figure('Annotation Interface')
63 | manager = plt.get_current_fig_manager()
64 | manager.resize(*manager.window.maxsize()) # maximize window
65 | plt.ion() # setup interactive mode
66 |
67 | for filename in files_to_annotate:
68 |
69 | if _KEEPannotating:
70 |
71 | # read image
72 | imagepath = path.join(cfg['required']['source'], filename)
73 | image = np.array(Image.open(imagepath))
74 |
75 | # image level status flags
76 | _ANNOinit = False
77 | _lastANNOwrong = False
78 | _SKIP_IMAGE = False
79 |
80 | # -----Setup figure for annotating -----
81 | ui.clear()
82 |
83 | gs = ui.add_gridspec(2, 2, width_ratios=[5, 1], height_ratios=[11, 1])
84 | # setup window for images
85 | ui_img = ui.add_subplot(gs[0])
86 | ui_img.axis('off')
87 | ui_img.imshow(image)
88 | # window for annotation instructions
89 | ui_instruct = ui.add_subplot(gs[1], sharex=ui_img, sharey=ui_img)
90 | ui_instruct.axis('off')
91 | instruct_msg = ui_instruct.text(0, 0,
92 | 'Instructions:\n'
93 | '1. Use the left mouse button to select the\n'
94 | 'following four extreme points for an object:\n'
95 | '- left,\n'
96 | '- right,\n'
97 | '- top, and\n'
98 | '- bottom.\n\n'
99 | '2. In case of misselection, use right mouse\n'
100 | 'button to undo.\n\n'
101 | '3. When the 4 points are selected, the\n'
102 | 'resulting masks are overlayed.\n\n'
103 | '4. Status messages are displayed at bottom\n'
104 | 'of the image; provide input based on them.\n\n'
105 | '5. Close window to exit.',
106 | fontsize=12, wrap=True, va='top', ha='left')
107 | # window for displaying status
108 | ui_status = ui.add_subplot(gs[2], sharey=ui_img) # window for displaying status
109 | ui_status.axis('off')
110 |
111 | # hold predictions from image
112 | image_results = []
113 |
114 | # keep running till user says he had finished annotating all objects in an image
115 | while True:
116 |
117 | if not _ANNOinit:
118 | ui_msg = ui_status.text(0, 0, 'Start annotation...', color='green', wrap=True, fontsize=14,
119 | va='top', ha='left')
120 | _ANNOinit = True
121 |
122 | elif _ANNOinit:
123 | if not _lastANNOwrong:
124 | ui_msg = ui_status.text(0, 0, 'Continue annotation...', color='green', wrap=True,
125 | fontsize=14, va='top', ha='left')
126 | elif _lastANNOwrong:
127 | ui_img.imshow(helpers.overlay_masks(image / 255, image_results))
128 | ui_msg = ui_status.text(0, 0, 'Ok. try again...', color='green', wrap=True,
129 | fontsize=14, va='top', ha='left')
130 |
131 |
132 | # user input required
133 | extreme_points_ori = np.array(plt.ginput(4, timeout=0, mouse_add=1)).astype(np.int)
134 |
135 | ui_msg.remove()
136 |
137 | # Crop image to the bounding box from the extreme points and resize
138 | bbox = helpers.get_bbox(image, points=extreme_points_ori, pad=pad, zero_pad=True)
139 | crop_image = helpers.crop_from_bbox(image, bbox, zero_pad=True)
140 | resize_image = helpers.fixed_resize(crop_image, (512, 512)).astype(np.float32)
141 |
142 | # Generate extreme point heat map normalized to image values
143 | extreme_points = extreme_points_ori - [np.min(extreme_points_ori[:, 0]),
144 | np.min(extreme_points_ori[:, 1])] + [pad, pad]
145 | extreme_points = (512 * extreme_points * [1 / crop_image.shape[1], 1 / crop_image.shape[0]]).astype(
146 | np.int)
147 | extreme_heatmap = helpers.make_gt(resize_image, extreme_points, sigma=10)
148 | extreme_heatmap = helpers.cstm_normalize(extreme_heatmap, 255)
149 |
150 | # Concatenate inputs and convert to tensor
151 | input_dextr = np.concatenate((resize_image, extreme_heatmap[:, :, np.newaxis]), axis=2)
152 |
153 | # Run a forward pass
154 | pred = net.model.predict(input_dextr[np.newaxis, ...])[0, :, :, 0]
155 | result = helpers.crop2fullmask(pred, bbox, im_size=image.shape[:2], zero_pad=True, relax=pad) > thres
156 |
157 | # Mask correct or not
158 | image_results.append(result) # add result to list of results even if incorrect for vis purposes
159 | plot_mask = ui_img.imshow(helpers.overlay_masks(image / 255, image_results))
160 |
161 | if _lastANNOwrong:
162 | ui_msg = ui_status.text(0, 0, 'Is the mask now correct? Click left mouse for yes, press \'n\' '
163 | 'for no.',
164 | color='orange', wrap=True, fontsize=14, va='top', ha='left')
165 | usr_choice = plt.waitforbuttonpress()
166 | if usr_choice:
167 | ui_msg.remove()
168 | ui_msg = ui_status.text(0, 0, 'Okay, to try annotating one more time click left mouse or '
169 | 'press \'n\' to skip to the new image.',
170 | color='red', wrap=True, fontsize=14, va='top', ha='left')
171 | usr_choice_skip = plt.waitforbuttonpress()
172 | if usr_choice_skip:
173 | ui_msg.remove()
174 | _SKIP_IMAGE = True
175 | _lastANNOwrong = False
176 | break
177 | else:
178 | ui_msg.remove()
179 | wrong_anno_mask = image_results.pop()
180 | _lastANNOwrong = True
181 | continue
182 | else:
183 | _lastANNOwrong = False
184 | ui_msg.remove()
185 | else:
186 | ui_msg = ui_status.text(0, 0, 'Is the generated mask correct? Click left mouse for yes, press'
187 | ' \'r\' to redo.',
188 | color='orange', wrap=True, fontsize=14, va='top', ha='left')
189 | not_anno_correct = plt.waitforbuttonpress()
190 | ui_msg.remove()
191 | if not_anno_correct:
192 | wrong_anno_mask = image_results.pop()
193 | _lastANNOwrong = True
194 | continue
195 |
196 | # Add extreme points to show annotation done for the object
197 | ui_img.plot(extreme_points_ori[:, 0], extreme_points_ori[:, 1], 'gx')
198 | # Check what user wants to do next
199 | ui_msg = ui_status.text(0, 0, 'Click left mouse to continue annotating this image or press \'d\''
200 | ' if done.',
201 | color='orange', wrap=True, fontsize=14, va='top', ha='left')
202 | usr_choice = plt.waitforbuttonpress()
203 | ui_msg.remove()
204 |
205 | if usr_choice: # if user presses d then break
206 | ui_msg = ui_status.text(0, 0, 'Annotation of this image stopped, mask image saved and progress'
207 | ' updated',
208 | color='red', wrap=True, fontsize=14, va='top', ha='left')
209 | break
210 |
211 | if _SKIP_IMAGE: # check if the break was initialised by skipping image
212 | tools.prog_update_skip(cfg, filename) # update prog file
213 | continue # if so, then continue on to next image
214 |
215 | # Show and save the generated masks
216 | generated_mask = tools.get_img_segmasks(image, image_results)
217 | mask_uint8 = tools.save_mask(generated_mask, cfg, filename)
218 |
219 | # -----Setup figure for showing annotation results -----
220 | ui.clear()
221 | # update figure to show subplots
222 | gs_res = ui.add_gridspec(2, 2, height_ratios=[11, 1])
223 | # subplot-1: image
224 | ui_res_img = ui.add_subplot(gs_res[0])
225 | ui_res_img.axis('off')
226 | ui_res_img.imshow(image)
227 | ui_res_img.set_title('Original Image')
228 | # subplot-2: mask image
229 | ui_res_mask = ui.add_subplot(gs_res[1])
230 | ui_res_mask.axis('off')
231 | ui_res_mask.imshow(mask_uint8, cmap='gray')
232 | ui_res_mask.set_title('Mask Image\n Note: Mask value scaled to [0 255] for visualisation')
233 | # subplot-3: status message
234 | ui_res_status = ui.add_subplot(gs_res[2], sharey=ui_res_img) # window for displaying status
235 | ui_res_status.axis('off')
236 | ui_res_msg = ui_res_status.text(0.0, 0.0, 'Annotate next image? Click left mouse for yes or press \'e\''
237 | ' to exit annotation and resume later',
238 | color='orange', wrap=True, fontsize=14, va='top', ha='left')
239 |
240 | # user input required
241 | usr_choice = plt.waitforbuttonpress()
242 | if usr_choice: # if user presses e then break
243 | _KEEPannotating = False
244 | ui_res_msg.remove()
245 | else:
246 | print("Annotation of images stopped. Your progress has been saved. Run script again to resume "
247 | "annotation. Exiting...")
248 | exit(0)
249 |
250 | print("Well Done...Finished annotating all files in the source folder. Exiting...")
251 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------