81 |
82 |
--------------------------------------------------------------------------------
/predict.py:
--------------------------------------------------------------------------------
1 | import argparse
2 |
3 | import imageio
4 | import numpy as np
5 |
6 | from tensorflow.keras.models import load_model
7 | from PIL import Image, ImageOps
8 | from tqdm import tqdm
9 | from utils import draw_predictions, compute_metrics
10 |
11 |
12 | def main(args):
13 | video = imageio.get_reader(args.video)
14 | n_frames = video.count_frames()
15 | fps = video.get_meta_data()['fps']
16 | frame_w, frame_h = video.get_meta_data()['size']
17 |
18 | model = load_model(args.model, compile=False)
19 | input_shape = model.input.shape[1:3]
20 |
21 | # default RoI
22 | if None in (args.rl, args.rt, args.rr, args.rb):
23 | side = min(frame_w, frame_h)
24 | args.rl = (frame_w - side) / 2
25 | args.rt = (frame_h - side) / 2
26 | args.rr = (frame_w + side) / 2
27 | args.rb = (frame_h + side) / 2
28 |
29 | crop = (args.rl, args.rt, args.rr, args.rb)
30 |
31 | def preprocess(frame):
32 | frame = Image.fromarray(frame)
33 | eye = frame.crop(crop)
34 | eye = ImageOps.grayscale(eye)
35 | eye = eye.resize(input_shape)
36 | return eye
37 |
38 | def predict(eye):
39 | eye = np.array(eye).astype(np.float32) / 255.0
40 | eye = eye[None, :, :, None]
41 | return model.predict(eye)
42 |
43 | out_video = imageio.get_writer(args.output_video, fps=fps)
44 |
45 | cropped = map(preprocess, video)
46 | frames_and_predictions = map(lambda x: (x, predict(x)), cropped)
47 |
48 | with open(args.output_csv, 'w') as out_csv:
49 | print('frame,pupil-area,pupil-x,pupil-y,eye,blink', file=out_csv)
50 | for idx, (frame, predictions) in enumerate(tqdm(frames_and_predictions, total=n_frames)):
51 | pupil_map, tags = predictions
52 | is_eye, is_blink = tags.squeeze()
53 | (pupil_y, pupil_x), pupil_area = compute_metrics(pupil_map, thr=args.thr, nms=True)
54 |
55 | row = [idx, pupil_area, pupil_x, pupil_y, is_eye, is_blink]
56 | row = ','.join(list(map(str, row)))
57 | print(row, file=out_csv)
58 |
59 | img = draw_predictions(frame, predictions, thr=args.thr)
60 | img = np.array(img)
61 | out_video.append_data(img)
62 |
63 | out_video.close()
64 |
65 |
66 | if __name__ == '__main__':
67 | parser = argparse.ArgumentParser(description='Predict on test video')
68 | parser.add_argument('model', type=str, help='Path to model')
69 | parser.add_argument('video', type=str, default='', help='Video file to process (use \'\' for webcam)')
70 |
71 | parser.add_argument('-t', '--thr', type=float, default=0.5, help='Map Threshold')
72 | parser.add_argument('-rl', type=int, help='RoI X coordinate of top left corner')
73 | parser.add_argument('-rt', type=int, help='RoI Y coordinate of top left corner')
74 | parser.add_argument('-rr', type=int, help='RoI X coordinate of right bottom corner')
75 | parser.add_argument('-rb', type=int, help='RoI Y coordinate of right bottom corner')
76 |
77 | parser.add_argument('-ov', '--output-video', default='predictions.mp4', help='Output video')
78 | parser.add_argument('-oc', '--output-csv', default='pupillometry.csv', help='Output CSV')
79 |
80 | args = parser.parse_args()
81 | main(args)
82 |
--------------------------------------------------------------------------------
/models/unet.py:
--------------------------------------------------------------------------------
1 | import tensorflow as tf
2 | from tensorflow.keras import layers as L
3 | from tensorflow.keras.models import Model
4 |
5 |
6 | def build_model(x_shape, y_shape, config):
7 | inp = L.Input(shape=x_shape)
8 | x = inp
9 |
10 | n_stages = config.get('num_stages', 2)
11 | n_conv = config.get('num_conv', 1)
12 | n_filters = config.get('num_filters', 16)
13 | grow_mult = config.get('grow_factor', 1)
14 | up_activation = config.get('up_act', 'relu')
15 | conv_type = config.get('conv_type', 'conv')
16 | use_aspp = config.get('aspp', False)
17 |
18 | if up_activation == 'lrelu':
19 | up_activation = L.LeakyReLU()
20 | else:
21 | up_activation = L.Activation(up_activation)
22 |
23 | use_bn = 'bn-' not in conv_type
24 |
25 | conv = L.SeparableConv2D if 'sep-' in conv_type else L.Conv2D
26 | conv_common = dict(padding='same', use_bias=not use_bn)
27 |
28 | def conv_block(*args, **kwargs):
29 | def layer(x):
30 | if use_bn:
31 | act = kwargs.pop('activation', None)
32 | x = conv(*args, **kwargs)(x)
33 | x = L.BatchNormalization()(x)
34 | return L.Activation(act)(x) if act else x
35 | return conv(*args, **kwargs)(x)
36 |
37 | return layer
38 |
39 | intermediate = []
40 |
41 | for _ in range(n_conv):
42 | x = conv_block(n_filters, 3, activation='relu', **conv_common)(x)
43 |
44 | # downsample path
45 | for i in range(n_stages):
46 | intermediate.append(x)
47 | n = round(n_filters * (grow_mult ** i))
48 | x = conv_block(n, 3, 2, activation='relu', **conv_common)(x)
49 | for _ in range(n_conv - 1):
50 | x = conv_block(n, 3, activation='relu', **conv_common)(x)
51 |
52 | middle = L.GlobalAveragePooling2D()(x)
53 |
54 | if use_aspp:
55 | n = round(n / 4)
56 | x1 = conv_block(n, 1, dilation_rate=1, activation='relu', **conv_common)(x)
57 | x2 = conv_block(n, 3, dilation_rate=2, activation='relu', **conv_common)(x)
58 | x3 = conv_block(n, 3, dilation_rate=4, activation='relu', **conv_common)(x)
59 | x4 = conv_block(n, 3, dilation_rate=6, activation='relu', **conv_common)(x)
60 |
61 | # global feature
62 | xg = L.Reshape((1, 1, -1))(middle)
63 | xg = conv_block(n, 1, activation='relu', **conv_common)(xg)
64 | feature_tiling = tf.pad(tf.shape(x)[1:3], tf.constant([[1, 1]]), constant_values=1)
65 | xg = tf.tile(xg, feature_tiling)
66 |
67 | x = tf.concat([x1, x2, x3, x4, xg], axis=-1)
68 |
69 | # upsample path
70 | for i in range(n_stages - 1, -1, -1):
71 | x = L.UpSampling2D(size=2, interpolation='bilinear')(x)
72 | x = L.Concatenate()([x, intermediate.pop()])
73 | n = round(n_filters * (grow_mult ** i))
74 | for _ in range(n_conv):
75 | x = conv_block(n, 3, **conv_common)(x)
76 | x = up_activation(x)
77 |
78 | # segmentation mask
79 | out_mask = conv(y_shape[-1], 3, activation='sigmoid', padding='same', name='mask')(x)
80 | # metadata tags (is_eye and is_blink)
81 | out_tags = L.Dense(2, activation='sigmoid', name='tags')(middle)
82 |
83 | return Model(inp, [out_mask, out_tags])
84 |
85 |
86 | if __name__ == '__main__':
87 | shape = (128, 128, 1)
88 | model = build_model(shape, shape, {'aspp': True})
89 | model.summary()
--------------------------------------------------------------------------------
/models/deeplab.py:
--------------------------------------------------------------------------------
1 | import sys
2 | sys.path += ['models/deeplab']
3 |
4 | import tensorflow as tf
5 |
6 | from tensorflow.keras import backend as K
7 | from tensorflow.keras import layers as L
8 | from tensorflow.keras.models import Model, Sequential
9 |
10 | from deeplabv3p.models.deeplabv3p_resnet50 import Deeplabv3pResNet50
11 | from deeplabv3p.models.deeplabv3p_mobilenetv3 import Deeplabv3pMobileNetV3Small, Deeplabv3pLiteMobileNetV3Small, Deeplabv3pMobileNetV3Large, Deeplabv3pLiteMobileNetV3Large
12 | from deeplabv3p.models.deeplabv3p_xception import Deeplabv3pXception
13 | from deeplabv3p.models.deeplabv3p_peleenet import Deeplabv3pPeleeNet, Deeplabv3pLitePeleeNet
14 |
15 | AVAILABLE_BACKBONES = {
16 | 'resnet50': Deeplabv3pResNet50,
17 | 'xception': Deeplabv3pXception,
18 | 'mobilenetv3-large': Deeplabv3pMobileNetV3Large,
19 | 'lite-mobilenetv3-large': Deeplabv3pLiteMobileNetV3Large,
20 | 'mobilenetv3-small': Deeplabv3pMobileNetV3Small,
21 | 'lite-mobilenetv3-small': Deeplabv3pLiteMobileNetV3Small,
22 | 'peleenet': Deeplabv3pPeleeNet,
23 | 'lite-peleenet': Deeplabv3pLitePeleeNet,
24 | }
25 |
26 | AVAILABLE_PRETRAINED_WEIGHTS = {
27 | 'resnet50': 'imagenet',
28 | 'xception': None, # 'pascalvoc', # needs fix in upstream
29 | 'mobilenetv3-large': 'imagenet',
30 | 'lite-mobilenetv3-large': 'imagenet',
31 | 'mobilenetv3-small': 'imagenet',
32 | 'lite-mobilenetv3-small': 'imagenet',
33 | 'peleenet': 'imagenet',
34 | 'lite-peleenet': 'imagenet',
35 | }
36 |
37 | def build_model(input_shape, output_shape, config):
38 |
39 | assert input_shape[:2] == output_shape[:2], "Only same input-output HW shapes are supported."
40 | num_classes = output_shape[2]
41 |
42 | # backbone pretends RGB images to use pretrained weights
43 | needs_rgb_conversion = input_shape[2] != 3
44 | backbone_input_shape = (input_shape[:2] + (3,)) if needs_rgb_conversion else input_shape
45 | backbone_name = config.get('backbone', 'resnet50')
46 | weights = config.get('weights', AVAILABLE_PRETRAINED_WEIGHTS[backbone_name])
47 | backbone_fn = AVAILABLE_BACKBONES[backbone_name]
48 | backbone, backbone_len = backbone_fn(input_shape=backbone_input_shape, num_classes=num_classes, weights=weights, OS=8)
49 |
50 | # segmentation mask
51 | out_mask = backbone.get_layer('pred_resize').output
52 | out_mask = L.Activation('sigmoid', name='mask')(out_mask)
53 |
54 | # metadata tags (is_eye and is_blink)
55 | middle = backbone.get_layer('image_pooling').output
56 | middle = L.Flatten()(middle)
57 | out_tags = L.Dense(2, activation='sigmoid', name='tags')(middle)
58 |
59 | model = Model(inputs=backbone.input, outputs=[out_mask, out_tags])
60 |
61 | if needs_rgb_conversion:
62 | gray_input = L.Input(shape=input_shape)
63 | rgb_input = L.Lambda(lambda x: K.tile(x, (1, 1, 1, 3)) , name='gray2rgb')(gray_input) # we assume BHWC
64 | out_mask, out_tags = model(rgb_input)
65 |
66 | # rename outputs
67 | out_mask = L.Lambda(lambda x: x, name='mask')(out_mask)
68 | out_tags = L.Lambda(lambda x: x, name='tags')(out_tags)
69 | model = Model(inputs=gray_input, outputs=[out_mask, out_tags])
70 |
71 | return model
72 |
73 |
74 | if __name__ == "__main__":
75 | shape = (128, 128, 1)
76 | model = build_model(shape, shape, {'weights': None})#, 'backbone': 'lite-mobilenetv3-small'})
77 | model.summary()
78 | import pdb; pdb.set_trace()
79 |
--------------------------------------------------------------------------------
/utils.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import matplotlib.pyplot as plt
3 |
4 | from PIL import Image, ImageDraw
5 | from scipy.ndimage import center_of_mass, label, sum as area
6 |
7 |
8 | def nms_on_area(x, s): # x is a binary image, s is a structuring element
9 | labels, num_labels = label(x, structure=s) # find connected components
10 | if num_labels > 1:
11 | indexes = np.arange(1, num_labels + 1)
12 | areas = area(x, labels, indexes) # compute area for each connected components
13 |
14 | biggest = max(zip(areas, indexes))[1] # get index of largest component
15 | x[labels != biggest] = 0 # discard other components
16 |
17 | return x
18 |
19 |
20 | def compute_metrics(p, thr=None, nms=False):
21 | p = p.squeeze()
22 |
23 | if thr:
24 | p = p > thr
25 | if nms: # perform non-maximum suppression: keep only largest area
26 | s = np.ones((3, 3)) # connectivity structure
27 | p = nms_on_area(p, s)
28 |
29 | center = center_of_mass(p)
30 | area = p.sum()
31 | return center, area
32 |
33 |
34 | def visualizable(x, y, alpha=(.5, .5), thr=0):
35 | xx = np.tile(x, (3,)) # Gray -> RGB: repeat channels 3 times
36 | yy = (y, ) + (np.zeros_like(x),) * (3 - y.shape[-1])
37 | yy = np.concatenate(yy, axis=-1) # add a zero channels to pad to RGB
38 | mask = yy.max(axis=-1, keepdims=True) > thr # blend only where a prediction is present
39 | # mask = mask[:, :, None]
40 | return np.where(mask, alpha[0] * xx + alpha[1] * yy, xx)
41 |
42 |
43 | def draw_predictions(image, predictions, thr=None):
44 | x = image.convert('RGBA')
45 |
46 | maps, tags = predictions
47 | maps = maps[0] if maps.ndim == 4 else maps
48 | eye, blink = tags.squeeze()
49 | alpha = maps.max(axis=-1, keepdims=True)
50 | alpha = alpha > thr if thr is not None else alpha
51 |
52 | n_pad = 3 - maps.shape[-1]
53 | zero_channels = np.zeros(image.size + (n_pad,))
54 | y = np.concatenate((maps, zero_channels, alpha), axis=-1) # add pad and masked alpha channel
55 | y = (y * 255).astype(np.uint8)
56 | y = Image.fromarray(y).convert('RGBA')
57 |
58 | preview = Image.alpha_composite(x, y)
59 | draw = ImageDraw.Draw(preview)
60 | draw.text((5, 5), 'E: {: >3.1%} B:{: >3.1%}'.format(eye, blink), fill=(0, 0, 255))
61 | # draw.text((5, image.height - 5), ''.format(blink), fill=(255, 0, 0))
62 |
63 | return preview
64 |
65 |
66 | def visualize(x, y, out=None, thr=0, n_cols=4, width=20):
67 | n_rows = len(x) // n_cols
68 | fig, axes = plt.subplots(n_rows, n_cols, figsize=(width, width * n_rows // n_cols))
69 | y_masks, y_tags = y
70 |
71 | axes = axes.flatten() if isinstance(axes, np.ndarray) else (axes,)
72 |
73 | for xi, yi_mask, yi_tags, ax in zip(x, y_masks, y_tags, axes):
74 | i = visualizable(xi, yi_mask, thr=thr)
75 | ax.imshow(i, cmap=plt.cm.gray)
76 | ax.grid(False)
77 | if len(yi_tags) == 2:
78 | title = 'E: {:.1%} - B: {:.1%}'
79 | elif len(yi_tags) == 4:
80 | title = 'pE: {:.1%} - pB: {:.1%}\ntE: {:.1%} - tB: {:.1%}'
81 |
82 | ax.text(x=0.5, y=-0.02, s=title.format(*yi_tags), transform=ax.transAxes,
83 | ha='center', va='top',
84 | fontsize=width * 4 / 5, fontfamily='monospace')
85 | ax.set_axis_off()
86 |
87 | if out:
88 | plt.savefig(out, bbox_inches='tight')
89 | plt.close()
90 |
--------------------------------------------------------------------------------
/matlab/README.md:
--------------------------------------------------------------------------------
1 | # MEYE pupillometry on MATLAB
2 |
3 | > Try MEYE on a standalone [Web-App](https://www.pupillometry.it/)
4 |
5 | > Learn more on the original [MEYE repo](https://github.com/fabiocarrara/meye)
6 |
7 | > Label your own dataset with [pLabeler](https://github.com/LeonardoLupori/pLabeler)
8 |
9 | Starting from MATLAB version 2021b, MEYE is also available for use on MATLAB!
10 |
11 | Here's a brief tutorial on how to use it in you own experiments.
12 |
13 | ## What do you need?
14 |
15 | - [MATLAB 2021b](https://it.mathworks.com/products/matlab.html) or later
16 | - [MATLAB Image Processing Toolbox](https://it.mathworks.com/products/image.html)
17 | - [MATLAB Deep Learning Toolbox](https://it.mathworks.com/products/deep-learning.html)
18 | An additional _support package_ of this toolbox has to be downloaded manually from the Add-On explorer in MATLAB:
19 | - _Deep Learning Toolbox™ Converter for ONNX Model Format_
20 | 
21 | - A MEYE model in [ONNX](https://onnx.ai/) format. You can download our latest model [here](https://github.com/fabiocarrara/meye/releases).
22 | 
23 |
24 |
25 | ## Quick start!
26 |
27 | ```matlab
28 | % Create an instance of Meye
29 | meye = Meye('path/to/model.onnx');
30 |
31 | % Example 1
32 | % Make predictions on a single Image
33 | %
34 | % Load an image for which you want to predict the pupil
35 | img = imread('path/to/img.tif');
36 | % Make a prediction on a frame
37 | [pupil, isEye, isBlink] = meye.predictImage(img);
38 |
39 | % Example 2
40 | % Make predictions on a video file and preview the results
41 | %
42 | meye.predictMovie_Preview('path/to/video');
43 | ```
44 |
45 | ## Examples
46 |
47 | Inside the file [example.m](example.m) you can find 5 extensively commented examples of some use cases for MEYE on MATLAB.
48 | These examples require you to download example data from [here](https://drive.google.com/drive/folders/1BG6O5BEkwXkNKC_1XuB3H9wbx3DeNWwF?usp=sharing). To run the examples succesfully, make sure that the downloaded files are in the same folder as the `example.m` file.
49 |
50 | # Known issues
51 |
52 | ## Small issue with _Upsample_ layers
53 | When [importing](https://it.mathworks.com/help/deeplearning/ref/importonnxnetwork.html) a ONNX network, MATLAB tries to translate all the layers of the network from ONNX Operators to built-in MATLAB layers (see [here](https://it.mathworks.com/help/deeplearning/ref/importonnxnetwork.html#mw_dc6cd14c-e8d0-4370-af81-96626a888d9c)).
54 | This operation is not succesful for all the layers and MATLAB tries to overcome erros by automatically generating custom layers to replace the ones that it wasnt able to translate. These _custom_ layers are stored in a folder as MATLAB `.m` class files.
55 | We found a small bug in the way MATLAB translates `Upsample` layers while importing MEYE network. In particular, the custom generated layers perform the upsample with the `nearest` interpolation method, while it should be used the `linear` method for best results.
56 | For now, we solved this bug by automatically replacing the `nearest` method with the `linear` one in all the custom generated layers. This restores optimal performance with no additional computational costs, but it's a bit hacky.
57 | We hope that in future releases MATLAB's process of translation to its own built-in layers will be smoother and this trick will not be needed anymore.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # [*mEye*](https://www.pupillometry.it): A Deep Learning Tool for Pupillometry
2 |
3 | > ⭐ MEYE is available on **MATLAB**! Check it out [here](matlab/README.md)
4 |
5 | > Check out [pupillometry.it](https://www.pupillometry.it) for a ready-to-use web-based mEye pupillometry tool!
6 |
7 | This branch provides the Python code to make predictions and train/finetune models.
8 | If you are interested in the code of the pupillometry web app, check out the `gh-pages` branch.
9 |
10 | ## Requirements
11 | You need a Python 3 environment with the following packages installed:
12 |
13 | - tensorflow >= 2.4
14 | - imageio, imageio-ffmpeg
15 | - scipy
16 | - tqdm
17 |
18 | If you want to train models, you also need
19 |
20 | - adabelief_tf >= 0.2.1
21 | - pandas
22 | - sklearn
23 |
24 | We provide a [Dockerfile](./Dockerfile) for building an image with docker.
25 |
26 | ## Make Predictions with Pretrained Models
27 |
28 | You can make predictions with pretrained models on pre-recorded videos or webcam streams.
29 |
30 | 1. Download the [pretrained model](https://github.com/fabiocarrara/meye/releases/download/v0.1.1/meye-2022-01-24.h5). If you want to use the [old model](https://github.com/fabiocarrara/meye/releases/download/v0.1/meye-segmentation_i128_s4_c1_f16_g1_a-relu.hdf5), check out version [`v0.1` of this branch](https://github.com/fabiocarrara/meye/tree/v0.1). See available models in [Releases](https://github.com/fabiocarrara/meye/releases).
31 | 2. Check out the `pupillometry-offline-videos.ipynb` notebook for a complete example of pupillometry data analysis.
32 | 3. In alternative, we provide also the `predict.py` script that implements the basic loop to make predictions on video streams. E.g.:
33 |
34 | - ```bash
35 | # input: webcam (default)
36 | # prediction roi: biggest central square crop (default)
37 | # outputs: predictions.mp4, predictions.csv (default)
38 | predict.py path/to/model
39 | ```
40 |
41 | - ```bash
42 | # input: video file
43 | # prediction roi: left=80, top=80, right=208, bottom=208
44 | # outputs: video_with_predictions.mp4, pupil_metrics.csv
45 | predict.py path/to/model path/to/video.mp4 -rl 80 -rt 80 -rr 208 -rb 208 -ov video_with_predictions.mp4 -oc pupil_metrics.csv
46 | ```
47 | - ```bash
48 | # check all parameters with
49 | predict.py -h
50 | ```
51 |
52 | ## Training Models
53 |
54 | 1. Download our dataset ([NN_human_mouse_eyes.zip](https://doi.org/10.5281/zenodo.4488164), 246.4 MB) or prepare your dataset following our dataset's structure.
55 | > If you need to annotate your dataset, check out [pLabeler](https://github.com/LeonardoLupori/pLabeler), a MATLAB software for labeling pupil images.
56 |
57 | The dataset should be placed in `data/`.
58 |
59 | 2. If you are using a custom dataset, edit `train.py` to perform the train/validation/test split of your data.
60 |
61 | 3. Train with default parameters:
62 | ```bash
63 | python train.py -d data/
64 | ```
65 |
66 | - For a list of available parameters, run
67 | ```bash
68 | python train.py -h
69 | ```
70 |
71 | ## MATLAB support
72 | Starting from MATLAB version 2021b, MEYE is also available for use on MATLAB!
73 | A fully functional class and a tutorial for its use is available [here](matlab/README.md)!
74 |
75 |
76 | ## References
77 |
78 | ### Dataset
79 | [](https://doi.org/10.5281/zenodo.4488164)
80 |
81 | If you use our dataset, please cite:
82 |
83 | @dataset{raffaele_mazziotti_2021_4488164,
84 | author = {Raffaele Mazziotti and Fabio Carrara and Aurelia Viglione and Lupori Leonardo and Lo Verde Luca and Benedetto Alessandro and Ricci Giulia and Sagona Giulia and Amato Giuseppe and Pizzorusso Tommaso},
85 | title = {{Human and Mouse Eyes for Pupil Semantic Segmentation}},
86 | month = feb,
87 | year = 2021,
88 | publisher = {Zenodo},
89 | version = {1.0},
90 | doi = {10.5281/zenodo.4488164},
91 | url = {https://doi.org/10.5281/zenodo.4488164}
92 | }
93 |
--------------------------------------------------------------------------------
/train_dl.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """ MEye: Semantic Segmentation """
3 |
4 | import argparse
5 | import os
6 |
7 | os.sys.path += ['expman', 'models/deeplab']
8 | import matplotlib
9 | matplotlib.use('Agg')
10 |
11 | import matplotlib.pyplot as plt
12 |
13 | import math
14 | import numpy as np
15 | import pandas as pd
16 | import tensorflow as tf
17 | import tensorflowjs as tfjs
18 | from tensorflow.keras import backend as K
19 | from tensorflow.keras.models import load_model
20 | from tensorflow.keras.callbacks import ModelCheckpoint, LearningRateScheduler, CSVLogger
21 | from sklearn.model_selection import train_test_split
22 | from sklearn.metrics import classification_report, roc_curve, auc, precision_recall_curve, average_precision_score
23 | from adabelief_tf import AdaBeliefOptimizer
24 | from tqdm.keras import TqdmCallback
25 | from tqdm import tqdm
26 | from functools import partial
27 |
28 | from dataloader import get_loader, load_datasets
29 | from deeplabv3p.models.deeplabv3p_mobilenetv3 import hard_swish
30 | from models.deeplab import build_model, AVAILABLE_BACKBONES
31 | from utils import visualize
32 | from expman import Experiment
33 |
34 | import evaluate
35 |
36 |
37 | def main(args):
38 | exp = Experiment(args, ignore=('epochs', 'resume'))
39 | print(exp)
40 |
41 | np.random.seed(args.seed)
42 | tf.random.set_seed(args.seed)
43 |
44 | data = load_datasets(args.data)
45 |
46 | # TRAIN/VAL/TEST SPLIT
47 | if args.split == 'subjects': # by SUBJECTS
48 | val_subjects = (6, 9, 11, 13, 16, 28, 30, 48, 49)
49 | test_subjects = (3, 4, 19, 38, 45, 46, 51, 52)
50 | train_data = data[~data['sub'].isin(val_subjects + test_subjects)]
51 | val_data = data[data['sub'].isin(val_subjects)]
52 | test_data = data[data['sub'].isin(test_subjects)]
53 |
54 | elif args.split == 'random': # 70-20-10 %
55 | train_data, valtest_data = train_test_split(data, test_size=.3, shuffle=True)
56 | val_data, test_data = train_test_split(valtest_data, test_size=.33)
57 |
58 | lengths = map(len, (data, train_data, val_data, test_data))
59 | print("Total: {} - Train / Val / Test: {} / {} / {}".format(*lengths))
60 |
61 | x_shape = (args.resolution, args.resolution, 1)
62 | y_shape = (args.resolution, args.resolution, 1)
63 |
64 | train_gen, _ = get_loader(train_data, batch_size=args.batch_size, shuffle=True, augment=True, x_shape=x_shape)
65 | val_gen, val_categories = get_loader(val_data, batch_size=args.batch_size, x_shape=x_shape)
66 | # test_gen, test_categories = get_loader(test_data, batch_size=1, x_shape=x_shape)
67 |
68 | log = exp.path_to('log.csv')
69 |
70 | # weights_only checkpoints
71 | best_weights_path = exp.path_to('best_weights.h5')
72 | best_mask_weights_path = exp.path_to('best_weights_mask.h5')
73 |
74 | # whole model checkpoints
75 | best_ckpt_path = exp.path_to('best_model.h5')
76 | last_ckpt_path = exp.path_to('last_model.h5')
77 |
78 | if args.resume and os.path.exists(last_ckpt_path):
79 | custom_objects={'AdaBeliefOptimizer': AdaBeliefOptimizer, 'iou_coef': evaluate.iou_coef, 'dice_coef': evaluate.dice_coef, 'hard_swish': hard_swish}
80 | model = tf.keras.models.load_model(last_ckpt_path, custom_objects=custom_objects)
81 | optimizer = model.optimizer
82 | initial_epoch = len(pd.read_csv(log))
83 | else:
84 | config = vars(args)
85 | model = build_model(x_shape, y_shape, config)
86 | optimizer = AdaBeliefOptimizer(learning_rate=args.lr, print_change_log=False)
87 | initial_epoch = 0
88 |
89 | model.compile(optimizer=optimizer,
90 | loss='binary_crossentropy',
91 | metrics={'mask': [evaluate.iou_coef, evaluate.dice_coef],
92 | 'tags': 'binary_accuracy'})
93 |
94 | model_stopped_file = exp.path_to('early_stopped.txt')
95 | need_training = not os.path.exists(model_stopped_file) and initial_epoch < args.epochs
96 | if need_training:
97 | best_checkpointer = ModelCheckpoint(best_weights_path, monitor='val_loss', save_best_only=True, save_weights_only=True)
98 | best_mask_checkpointer = ModelCheckpoint(best_mask_weights_path, monitor='val_mask_dice_coef', mode='max', save_best_only=True, save_weights_only=True)
99 | last_checkpointer = ModelCheckpoint(last_ckpt_path, save_best_only=False, save_weights_only=False)
100 | logger = CSVLogger(log, append=args.resume)
101 | progress = TqdmCallback(verbose=1, initial=initial_epoch, dynamic_ncols=True)
102 | early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_mask_dice_coef', mode='max', patience=100)
103 |
104 | callbacks = [best_checkpointer, best_mask_checkpointer, last_checkpointer, logger, progress, early_stop]
105 |
106 | model.fit(train_gen,
107 | epochs=args.epochs,
108 | callbacks=callbacks,
109 | initial_epoch=initial_epoch,
110 | steps_per_epoch=len(train_gen),
111 | validation_data=val_gen,
112 | validation_steps=len(val_gen),
113 | verbose=False)
114 |
115 | if model.stop_training:
116 | open(model_stopped_file, 'w').close()
117 |
118 | tf.keras.models.save_model(model, best_ckpt_path, include_optimizer=False)
119 |
120 | # evaluation on test set
121 | evaluate.evaluate(exp, force=need_training)
122 |
123 | # save best snapshot in SavedModel format
124 | model.load_weights(best_mask_weights_path)
125 | best_savedmodel_path = exp.path_to('best_savedmodel')
126 | model.save(best_savedmodel_path, save_traces=True)
127 |
128 | # export to tfjs (Layers model)
129 | tfjs_model_dir = exp.path_to('tfjs')
130 | tfjs.converters.save_keras_model(model, tfjs_model_dir)
131 |
132 |
133 | if __name__ == '__main__':
134 | default_data = ['data/NN_human_mouse_eyes']
135 |
136 | parser = argparse.ArgumentParser(description='Train DeepLab models')
137 | # data params
138 | parser.add_argument('-d', '--data', nargs='+', default=default_data, help='Data directory (may be multiple)')
139 | parser.add_argument('--split', default='random', choices=('random', 'subjects'), help='How to split data')
140 | parser.add_argument('-r', '--resolution', type=int, default=128, help='Input image resolution')
141 |
142 | # model params
143 | parser.add_argument('-a', '--backbone', default='resnet50', choices=AVAILABLE_BACKBONES, help='Backbone architecture')
144 |
145 | # train params
146 | parser.add_argument('--lr', type=float, default=0.001, help='learning rate')
147 | parser.add_argument('-b', '--batch-size', type=int, default=32, help='Batch size')
148 | parser.add_argument('-e', '--epochs', type=int, default=500, help='Number of training epochs')
149 | parser.add_argument('-s', '--seed', type=int, default=23, help='Random seed')
150 | parser.add_argument('--resume', default=False, action='store_true', help='Resume training')
151 |
152 | args = parser.parse_args()
153 | main(args)
154 |
--------------------------------------------------------------------------------
/matlab/example.m:
--------------------------------------------------------------------------------
1 | %% Download all the example material
2 | %
3 | % 1 - Download the latest MEYE model in ONNX format
4 | % -------------------------------------------------------------------------
5 | % Download the .onnx file from the assets here:
6 | % https://github.com/fabiocarrara/meye/releases
7 |
8 | % EXAMPLE data can be found in this folder:
9 | % https://drive.google.com/drive/folders/1BG6O5BEkwXkNKC_1XuB3H9wbx3DeNWwF?usp=sharing
10 | %
11 | % 2 - Download an example image of a simple mouse eye from:
12 | % https://drive.google.com/file/d/1hcWcC1cAmzY4r-SIWDIgUY0-gpbmetUL/view?usp=sharing
13 | %
14 | % 3 - Download an example of a large image here:
15 | % https://drive.google.com/file/d/16QixvUMtojqfrcy4WXlYJ7CP3K8vrz_C/view?usp=sharing
16 | %
17 | % 4 - Download an example pupillometry video here:
18 | % https://drive.google.com/file/d/1TYj80dzIR1ZjpEvfefH_akhbUjwpvJta/view?usp=sharing
19 |
20 |
21 | %% EXAMPLE 1
22 | % -------------------------------------------------------------------------
23 | % Predict the pupil from a simple image of an eye
24 |
25 | % Clean up the workspace
26 | clearvars, clc
27 |
28 | % Change these values according to the filenames of the MEYE model and the
29 | % simple pupil image
30 | MODEL_NAME = 'meye_20220124.onnx';
31 | IMAGE_NAME = 'pupilImage_simple.png';
32 |
33 |
34 | % Initialize a MEYE object
35 | meye = Meye(MODEL_NAME);
36 |
37 | % Load the simple image
38 | img = imread(IMAGE_NAME);
39 |
40 | % Predict a single image
41 | [pupilMask, eyeProb, blinkProb] = meye.predictImage(img);
42 |
43 | % Plot the results of the prediction
44 | subplot(1,3,1)
45 | imshow(img)
46 | title('Original Image')
47 |
48 | subplot(1,3,2)
49 | imagesc(pupilMask)
50 | title(sprintf('Prediction (Eye:%.2f%% - Blink:%.2f%%)',eyeProb*100,blinkProb*100))
51 | axis off, axis image
52 |
53 | subplot(1,3,3)
54 | imshowpair(img, pupilMask)
55 | title('Merge')
56 |
57 |
58 | %% EXAMPLE 2
59 | % -------------------------------------------------------------------------
60 | % Binarize the pupil prediction and get the pupil size in pixels
61 |
62 | % Clean up the workspace
63 | clearvars, close all, clc
64 |
65 | % Change these values according to the filenames of the MEYE model and the
66 | % simple pupil image
67 | MODEL_NAME = 'meye_20220124.onnx';
68 | IMAGE_NAME = 'pupilImage_simple.png';
69 |
70 |
71 | % Initialize a MEYE object
72 | meye = Meye(MODEL_NAME);
73 |
74 | % Load the simple image
75 | img = imread(IMAGE_NAME);
76 |
77 | % Predict a single image
78 | % You can automatically binarize the prediction by passing the "threshold"
79 | % optional argument. This number can be between 0 and 1. If omitted, the
80 | % function returns a raw probability map instead of a binarized image
81 | pupilBinaryMask = meye.predictImage(img, 'threshold', 0.4);
82 |
83 | imshowpair(img, pupilBinaryMask)
84 | title(sprintf('Pupil Size: %u px', sum(pupilBinaryMask,'all')))
85 |
86 |
87 | %% EXAMPLE 3
88 | % -------------------------------------------------------------------------
89 | % Predict the pupil on a large image where the eye is a small portion of
90 | % the image
91 |
92 | % Clean up the workspace
93 | clearvars, close all, clc
94 |
95 | % Change these values according to the filenames of the MEYE model and the
96 | % simple pupil image
97 | MODEL_NAME = 'meye_20220124.onnx';
98 | IMAGE_NAME = 'pupilImage_large.png';
99 |
100 |
101 | % Initialize a MEYE object
102 | meye = Meye(MODEL_NAME);
103 |
104 | % Load the simple image
105 | img = imread(IMAGE_NAME);
106 |
107 | % Predict the image
108 | pupilMask = meye.predictImage(img);
109 |
110 | % As you can see from this image, the prediction is not perfect. This is
111 | % because MEYE was trained on images that tightly contained the eye.
112 | subplot(1,2,1)
113 | imshowpair(img, pupilMask)
114 | title('Tomal Image prediction (low-quality)')
115 |
116 | % In order to solve this issue it is possible to restrict the prediction to
117 | % a rectangular Region of Interest (ROI) in the image. This is done simply
118 | % by passing the optional argument "roiPos" to the predictImage function.
119 | % The roiPos is a 4-elements vector containing X,Y, width, height of a
120 | % rectangular shape. Note that X and Y are the coordinates of the top left
121 | % corner of the ROI
122 |
123 | ROI = [90,90,200,200];
124 | pupilMask = meye.predictImage(img, 'roiPos', ROI);
125 |
126 | % Plot the results with the ROI and see the difference between the 2 methods
127 | subplot(1,2,2)
128 | imshowpair(img, pupilMask)
129 | rectangle('Position',ROI, 'LineStyle','-.','EdgeColor',[1,0,0])
130 | title('ROI prediction (high quality)')
131 | linkaxes
132 | set(gcf,'Position',[300,600,1000,320])
133 |
134 |
135 | %% EXAMPLE 4
136 | % -------------------------------------------------------------------------
137 | % Show a preview of the prediction of an entire pupillometry video.
138 | %
139 | % As you saw you can adjust a few parameters for the prediction.
140 | % If you want to get a quick preview of how your pre-recorded video will be
141 | % processed, you can use the method predictMovie_Preview.
142 | % Here you can play around with different ROI positions and threshold
143 | % values and see what are the results before analyzing the whole video.
144 |
145 | % Clean up the workspace
146 | clearvars, close all, clc
147 |
148 | % Change these values according to the filenames of the MEYE model and the
149 | % simple pupil image
150 | MODEL_NAME = 'meye_20220124.onnx';
151 | VIDEO_NAME = 'mouse_example.mp4';
152 |
153 | % Initialize a MEYE object
154 | meye = Meye(MODEL_NAME);
155 |
156 | % Try to play around moving or resizing the ROI to see how the performances change
157 | ROI = [70, 60, 200, 200];
158 |
159 | % Change the threshold value to binarize the pupil prediction.
160 | % Use [] to see the raw probability map. Use a number in the range [0:1] to binarize it
161 | threshold = 0.4;
162 |
163 | meye.predictMovie_Preview(VIDEO_NAME,"roiPos", ROI,"threshold",threshold);
164 |
165 |
166 |
167 | %% EXAMPLE 5
168 | % Predict the entire video and get the results table
169 |
170 | % Clean up the workspace
171 | clearvars, close all, clc
172 |
173 | % Change these values according to the filenames of the MEYE model and the
174 | % simple pupil image
175 | MODEL_NAME = 'meye_20220124.onnx';
176 | VIDEO_NAME = 'mouse_example.mp4';
177 |
178 | % Initialize a MEYE object
179 | meye = Meye(MODEL_NAME);
180 |
181 | % Try to play around moving or resizing the ROI to see how the performances change
182 | ROI = [70, 60, 200, 200];
183 |
184 | % Change the threshold value to binarize the pupil prediction.
185 | % Use [] to see the raw probability map. Use a number in the range [0:1] to binarize it
186 | threshold = 0.4;
187 |
188 | % Predict the whole movie and save results in a table
189 | T = meye.predictMovie(VIDEO_NAME, "roiPos", ROI, "threshold", threshold);
190 |
191 | % Show some of the values in the table
192 | disp(head(T))
193 |
194 | % Plot some of the results
195 | subplot 311
196 | plot(T.frameTime,T.isEye, 'LineWidth', 2)
197 | title('Eye Probability')
198 | ylabel('Probability'),
199 | xlim([T.frameTime(1) T.frameTime(end)])
200 |
201 | subplot 312
202 | plot(T.frameTime,T.isBlink, 'LineWidth', 2)
203 | title('Blink Probability')
204 | ylabel('Probability')
205 | xlim([T.frameTime(1) T.frameTime(end)])
206 |
207 | subplot 313
208 | plot(T.frameTime,T.pupilArea, 'LineWidth', 2)
209 | title('Pupil Size')
210 | xlabel('Time (s)'), ylabel('Pupil Area (px)')
211 | xlim([T.frameTime(1) T.frameTime(end)])
212 |
--------------------------------------------------------------------------------
/dataloader.py:
--------------------------------------------------------------------------------
1 | import os
2 | import math
3 | import pandas as pd
4 | import tensorflow as tf
5 | import tensorflow_addons as tfa
6 |
7 | from functools import partial
8 |
9 | # find pupil center
10 | def _get_pupil_position(pmap, datum, x_shape):
11 | total_mass = tf.reduce_sum(pmap)
12 | if total_mass > 0:
13 | shape = tf.shape(pmap)
14 | h, w = shape[0], shape[1]
15 | ii, jj = tf.meshgrid(tf.range(h), tf.range(w), indexing='ij')
16 | y = tf.reduce_sum(tf.cast(ii, 'float32') * pmap) / total_mass
17 | x = tf.reduce_sum(tf.cast(jj, 'float32') * pmap) / total_mass
18 | return tf.stack((y, x))
19 |
20 | if 'roi_x' in datum and 'roi_y' in datum and 'roi_w' in datum:
21 | roi_x = tf.cast(datum['roi_x'], 'float32')
22 | roi_y = tf.cast(datum['roi_y'], 'float32')
23 | half = tf.cast(datum['roi_w'] / 2, 'float32')
24 | result = tf.stack((roi_y + half, roi_x + half))
25 | else: # fallback to center of the image
26 | result = tf.cast(tf.stack((x_shape[0] / 2, x_shape[1] / 2)), dtype='float32')
27 |
28 | return result
29 |
30 |
31 | @tf.function
32 | def load_datum(datum, x_shape=(128, 128, 1), augment=False):
33 |
34 | x = tf.io.read_file(datum['filename'])
35 | y = tf.io.read_file(datum['target'])
36 |
37 | # HWC [0,1] float32
38 | x = tf.io.decode_image(x, channels=1, dtype='float32', expand_animations=False)
39 | y = tf.io.decode_image(y, dtype='float32', expand_animations=False)
40 |
41 | shape = tf.cast(tf.shape(x), 'float32')
42 | h, w = shape[0], shape[1]
43 | half_wh = tf.stack((w, h)) / 2
44 |
45 | pupil_map = y[:, :, 0] # R-channel is the pupil map
46 | pupil_area = tf.reduce_sum(pupil_map)
47 |
48 | pupil_pos_yx = _get_pupil_position(pupil_map, datum, x_shape)
49 |
50 | if not augment:
51 | s = tf.minimum(tf.cast(x_shape[0], 'float32'), tf.minimum(h, w))
52 | pupil_pos_xy = pupil_pos_yx[::-1]
53 | pupil_new_pos_xy = tf.constant([.5, .5]) * s
54 |
55 | crop_xy = pupil_pos_xy - pupil_new_pos_xy # crop origin
56 | # find the feasibility region for the top-left corner of a square crop of size s
57 | crop_min, crop_max = tf.constant((0., 0.)), tf.stack((w - s, h - s))
58 | crop_xy = tf.clip_by_value(crop_xy, crop_min, crop_max)
59 |
60 | p = tfa.image.translations_to_projective_transforms(-crop_xy)
61 |
62 | else: # data augmentation
63 | # random rotation: pick random angle
64 | theta = tf.random.uniform([], 0, math.pi / 2)
65 | cos_t = tf.math.cos(theta)
66 | sin_t = tf.math.sin(theta)
67 |
68 | # random scale: pick random size of crop around the pupil
69 | # (constrained by the rotation angle and the original image size)
70 | min_s = 15
71 | max_s = tf.math.floor(tf.minimum(w, h) / (sin_t + cos_t))
72 | s = tf.random.normal([], mean=128, stddev=50)
73 | s = tf.clip_by_value(s, min_s, max_s)
74 |
75 | # find the feasibility region for the top-left corner of a square crop of size s
76 | crop_lt = tf.stack((s * sin_t, 0))
77 | crop_rb = tf.stack((w - s * cos_t, h - s * (sin_t + cos_t)))
78 |
79 | # pick a new random position (in the crop space) in which to place the pupil center
80 | std = 0.2 if (datum['blink'] == 1) else 0.5 # make sure blinking eyes are shown
81 | pupil_new_pos_yx = tf.random.normal((2,), mean=0.5, stddev=std) * s
82 |
83 | pupil_pos_y, pupil_pos_x = pupil_pos_yx[0], pupil_pos_yx[1]
84 | pupil_new_pos_y, pupil_new_pos_x = pupil_new_pos_yx[0], pupil_new_pos_yx[1]
85 |
86 | # crop origin (works.. but xy seem swapped, to double check)
87 | crop_xy = tf.stack((
88 | pupil_pos_y + pupil_new_pos_x * sin_t - pupil_new_pos_y * cos_t,
89 | pupil_pos_x - pupil_new_pos_x * cos_t - pupil_new_pos_y * sin_t
90 | ))
91 |
92 | # ensure crop is inside image
93 | crop_xy = tf.clip_by_value(crop_xy, crop_lt, crop_rb)
94 |
95 | # compose transformation
96 | tr1 = tfa.image.translations_to_projective_transforms(half_wh - crop_xy)
97 | rot = tfa.image.angles_to_projective_transforms(theta, h, w)
98 | tr2 = tfa.image.translations_to_projective_transforms(-half_wh)
99 | p = tfa.image.compose_transforms((tr1, rot, tr2))
100 |
101 | x = tfa.image.transform(x, p, output_shape=(s, s))
102 | y = tfa.image.transform(y, p, output_shape=(s, s))
103 |
104 | # compute how much pupil is left in the image
105 | new_pupil_map = y[:, :, 0]
106 | new_pupil_area = tf.reduce_sum(new_pupil_map)
107 | eye = (new_pupil_area / pupil_area) if pupil_area > 0 else 0.
108 |
109 | datum_eye = tf.cast(datum['eye'], 'float32')
110 | datum_blink = tf.cast(datum['blink'], 'float32')
111 | if datum_eye == 0: # set noblink if there is no eye
112 | datum_blink = 0.
113 |
114 | if (datum_eye == 1) & (datum_blink == 0): # update eye percentage due to crop (if no blink)
115 | datum_eye = eye
116 |
117 | if tf.math.reduce_any(tf.shape(x)[:2] != x_shape[:2]):
118 | x = tf.image.resize(x, x_shape[:2])
119 | y = tf.image.resize(y, x_shape[:2])
120 |
121 | if augment:
122 | # random flip
123 | if tf.random.uniform([]) < 0.5:
124 | x = tf.image.flip_left_right(x)
125 | y = tf.image.flip_left_right(y)
126 |
127 | if tf.random.uniform([]) < 0.5:
128 | x = tf.image.flip_up_down(x)
129 | y = tf.image.flip_up_down(y)
130 |
131 | # random brightness, contrast
132 | contrast_factor = tf.random.normal([], mean=1.0, stddev=0.4)
133 |
134 | x = tf.image.random_brightness(x, 0.2)
135 | x = tf.image.adjust_contrast(x, contrast_factor)
136 | x = tf.clip_by_value(x, 0, 1)
137 |
138 | y = y[:, :, :1]
139 | y2 = tf.stack((datum_eye, datum_blink))
140 |
141 | return x, y, y2
142 |
143 |
144 | def get_loader(dataframe, batch_size=8, shuffle=False, **kwargs):
145 | categories = dataframe.exp.values
146 |
147 | dataset = tf.data.Dataset.from_tensor_slices(dict(dataframe))
148 |
149 | if shuffle:
150 | dataset = dataset.shuffle(1000)
151 |
152 | dataset = dataset.map(partial(load_datum, **kwargs), num_parallel_calls=tf.data.AUTOTUNE, deterministic=not shuffle)
153 | dataset = dataset.batch(batch_size)
154 |
155 | # pack targets for keras
156 | def _pack_targets(*ins):
157 | inputs = ins[0]
158 | targets = {'mask': ins[1], 'tags': ins[2]}
159 | return [inputs, targets]
160 |
161 | dataset = dataset.map(_pack_targets, num_parallel_calls=tf.data.AUTOTUNE, deterministic=not shuffle)
162 | dataset = dataset.prefetch(tf.data.AUTOTUNE)
163 | return dataset, categories
164 |
165 |
166 | def load_datasets(dataset_dirs):
167 |
168 | def _load_and_prepare_annotations(dataset_dir):
169 | data = os.path.join(dataset_dir, 'annotation', 'annotations.csv')
170 | data = pd.read_csv(data)
171 | data['target'] = dataset_dir + '/annotation/png/' + data.filename.str.replace(r'jpe?g', 'png')
172 | data['filename'] = dataset_dir + '/fullFrames/' + data.filename
173 | return data
174 |
175 | dataset = pd.concat([_load_and_prepare_annotations(d) for d in dataset_dirs])
176 | dataset['sub'] = dataset['sub'].astype(str)
177 | return dataset
178 |
179 |
180 | if __name__ == '__main__':
181 | dataset = load_datasets(['NN_human_mouse_eyes'])
182 | loader, categories = get_loader(dataset, batch_size=1, shiffle=False)
183 |
184 | for x, y in loader:
185 | print(x, y)
186 | break
187 |
--------------------------------------------------------------------------------
/train.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """ MEye: Semantic Segmentation """
3 |
4 | import argparse
5 | import os
6 |
7 | os.sys.path += ['expman']
8 | import matplotlib
9 | matplotlib.use('Agg')
10 |
11 | import matplotlib.pyplot as plt
12 |
13 | import math
14 | import numpy as np
15 | import pandas as pd
16 | import tensorflow as tf
17 | import tensorflowjs as tfjs
18 | from tensorflow.keras import backend as K
19 | from tensorflow.keras.models import load_model
20 | from tensorflow.keras.callbacks import ModelCheckpoint, LearningRateScheduler, CSVLogger
21 | from sklearn.model_selection import train_test_split
22 | from sklearn.metrics import classification_report, roc_curve, auc, precision_recall_curve, average_precision_score
23 | from adabelief_tf import AdaBeliefOptimizer
24 | from tqdm.keras import TqdmCallback
25 | from tqdm import tqdm
26 | from functools import partial
27 |
28 | from dataloader import get_loader, load_datasets
29 | from models.unet import build_model
30 | from utils import visualize
31 | from expman import Experiment
32 |
33 | import evaluate
34 |
35 |
36 | def main(args):
37 | exp = Experiment(args, ignore=('epochs', 'resume'))
38 | print(exp)
39 |
40 | np.random.seed(args.seed)
41 | tf.random.set_seed(args.seed)
42 |
43 | data = load_datasets(args.data)
44 |
45 | # TRAIN/VAL/TEST SPLIT
46 | if args.split == 'subjects': # by SUBJECTS
47 | val_subjects = (6, 9, 11, 13, 16, 28, 30, 48, 49)
48 | test_subjects = (3, 4, 19, 38, 45, 46, 51, 52)
49 | train_data = data[~data['sub'].isin(val_subjects + test_subjects)]
50 | val_data = data[data['sub'].isin(val_subjects)]
51 | test_data = data[data['sub'].isin(test_subjects)]
52 |
53 | elif args.split == 'random': # 70-20-10 %
54 | train_data, valtest_data = train_test_split(data, test_size=.3, shuffle=True)
55 | val_data, test_data = train_test_split(valtest_data, test_size=.33)
56 |
57 | lengths = map(len, (data, train_data, val_data, test_data))
58 | print("Total: {} - Train / Val / Test: {} / {} / {}".format(*lengths))
59 |
60 | x_shape = (args.resolution, args.resolution, 1)
61 | y_shape = (args.resolution, args.resolution, 1)
62 |
63 | train_gen, _ = get_loader(train_data, batch_size=args.batch_size, shuffle=True, augment=True, x_shape=x_shape)
64 | val_gen, val_categories = get_loader(val_data, batch_size=args.batch_size, x_shape=x_shape)
65 | # test_gen, test_categories = get_loader(test_data, batch_size=1, x_shape=x_shape)
66 |
67 | log = exp.path_to('log.csv')
68 |
69 | # weights_only checkpoints
70 | best_weights_path = exp.path_to('best_weights.h5')
71 | best_mask_weights_path = exp.path_to('best_weights_mask.h5')
72 |
73 | # whole model checkpoints
74 | best_ckpt_path = exp.path_to('best_model.h5')
75 | last_ckpt_path = exp.path_to('last_model.h5')
76 |
77 | if args.resume and os.path.exists(last_ckpt_path):
78 | custom_objects={'AdaBeliefOptimizer': AdaBeliefOptimizer, 'iou_coef': evaluate.iou_coef, 'dice_coef': evaluate.dice_coef}
79 | model = tf.keras.models.load_model(last_ckpt_path, custom_objects=custom_objects)
80 | optimizer = model.optimizer
81 | initial_epoch = len(pd.read_csv(log))
82 | else:
83 | config = vars(args)
84 | model = build_model(x_shape, y_shape, config)
85 | optimizer = AdaBeliefOptimizer(learning_rate=args.lr, print_change_log=False)
86 | initial_epoch = 0
87 |
88 | model.compile(optimizer=optimizer,
89 | loss='binary_crossentropy',
90 | metrics={'mask': [evaluate.iou_coef, evaluate.dice_coef],
91 | 'tags': 'binary_accuracy'})
92 |
93 | model_stopped_file = exp.path_to('early_stopped.txt')
94 | need_training = not os.path.exists(model_stopped_file) and initial_epoch < args.epochs
95 | if need_training:
96 | best_checkpointer = ModelCheckpoint(best_weights_path, monitor='val_loss', save_best_only=True, save_weights_only=True)
97 | best_mask_checkpointer = ModelCheckpoint(best_mask_weights_path, monitor='val_mask_dice_coef', mode='max', save_best_only=True, save_weights_only=True)
98 | last_checkpointer = ModelCheckpoint(last_ckpt_path, save_best_only=False, save_weights_only=False)
99 | logger = CSVLogger(log, append=args.resume)
100 | progress = TqdmCallback(verbose=1, initial=initial_epoch, dynamic_ncols=True)
101 | early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_mask_dice_coef', mode='max', patience=100)
102 |
103 | callbacks = [best_checkpointer, best_mask_checkpointer, last_checkpointer, logger, progress, early_stop]
104 |
105 | model.fit(train_gen,
106 | epochs=args.epochs,
107 | callbacks=callbacks,
108 | initial_epoch=initial_epoch,
109 | steps_per_epoch=len(train_gen),
110 | validation_data=val_gen,
111 | validation_steps=len(val_gen),
112 | verbose=False)
113 |
114 | if model.stop_training:
115 | open(model_stopped_file, 'w').close()
116 |
117 | tf.keras.models.save_model(model, best_ckpt_path, include_optimizer=False)
118 |
119 | # evaluation on test set
120 | evaluate.evaluate(exp, force=need_training)
121 |
122 | # save best snapshot in SavedModel format
123 | model.load_weights(best_mask_weights_path)
124 | best_savedmodel_path = exp.path_to('best_savedmodel')
125 | model.save(best_savedmodel_path, save_traces=True)
126 |
127 | # export to tfjs (Layers model)
128 | tfjs_model_dir = exp.path_to('tfjs')
129 | tfjs.converters.save_keras_model(model, tfjs_model_dir)
130 |
131 |
132 | if __name__ == '__main__':
133 | default_data = ['data/NN_human_mouse_eyes']
134 |
135 | parser = argparse.ArgumentParser(description='')
136 | # data params
137 | parser.add_argument('-d', '--data', nargs='+', default=default_data, help='Data directory (may be multiple)')
138 | parser.add_argument('--split', default='random', choices=('random', 'subjects'), help='How to split data')
139 | parser.add_argument('-r', '--resolution', type=int, default=128, help='Input image resolution')
140 |
141 | # model params
142 | parser.add_argument('--num-stages', type=int, default=5, help='number of down-up sample stages')
143 | parser.add_argument('--num-conv', type=int, default=1, help='number of convolutions per stage')
144 | parser.add_argument('--num-filters', type=int, default=16, help='number of conv filter at first stage')
145 | parser.add_argument('--grow-factor', type=float, default=1.5,
146 | help='# filters at stage i = num-filters * grow-factor ** i')
147 | parser.add_argument('--up-activation', default='relu', choices=('relu', 'lrelu'),
148 | help='activation in upsample stages')
149 | parser.add_argument('--conv-type', default='conv', choices=('conv', 'bn-conv', 'sep-conv', 'sep-bn-conv'),
150 | help='convolution type')
151 | parser.add_argument('--use-aspp', default=False, action='store_true', help='Use Atrous Spatial Pyramid Pooling')
152 |
153 | # train params
154 | parser.add_argument('--lr', type=float, default=0.001, help='learning rate')
155 | parser.add_argument('-b', '--batch-size', type=int, default=32, help='Batch size')
156 | parser.add_argument('-e', '--epochs', type=int, default=1500, help='Number of training epochs')
157 | parser.add_argument('-s', '--seed', type=int, default=23, help='Random seed')
158 | parser.add_argument('--resume', default=False, action='store_true', help='Resume training')
159 |
160 | args = parser.parse_args()
161 | main(args)
162 |
--------------------------------------------------------------------------------
/show.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import math
3 | import os
4 | os.sys.path += ['expman']
5 |
6 | import matplotlib
7 | matplotlib.use('Agg')
8 | import matplotlib.pyplot as plt
9 | import matplotlib.ticker as ticker
10 | from matplotlib.image import imread
11 | from matplotlib.backends.backend_pdf import PdfPages
12 |
13 | import numpy as np
14 | import pandas as pd
15 | import seaborn as sns
16 |
17 | from glob import glob
18 |
19 | import expman
20 |
21 |
22 | def ee(args):
23 | sns.set_theme(context='notebook', style='whitegrid')
24 |
25 | exps = expman.gather(args.run).filter(args.filter)
26 | mask_metrics = exps.collect('test_pred/mask_metrics.csv').groupby('exp_id')[['dice', 'iou']].max()
27 | flops_nparams = exps.collect('flops_nparams.csv')
28 | data = pd.merge(mask_metrics, flops_nparams, on='exp_id')
29 | data['dice'] *= 100
30 |
31 | named_data = data.rename({
32 | 'nparams': '# Params',
33 | 'dice': 'mean Dice Coeff. (%)',
34 | 'conv_type': '$t$ (Conv. Type)',
35 | 'grow_factor': r'$\gamma$',
36 | 'num_filters': '$k$ (# Filters)',
37 | 'flops': 'FLOPs',
38 | 'num_stages': '$s$ (# Stages)',
39 | }, axis=1).replace({
40 | 'bn-conv': 'conv-bn',
41 | 'sep-bn-conv': 'sep-conv-bn'
42 | })
43 |
44 | g = sns.relplot(data=named_data,
45 | x='FLOPs', y='mean Dice Coeff. (%)',
46 | hue='$t$ (Conv. Type)',
47 | hue_order=['conv', 'conv-bn', 'sep-conv', 'sep-conv-bn'],
48 | col='$s$ (# Stages)', style='$k$ (# Filters)', markers=True, markersize=9,
49 | kind='line', dashes=True, facet_kws=dict(despine=False, legend_out=False), legend=True,
50 | height=3.8, aspect=1.3, markeredgecolor='white')
51 |
52 | b_formatter = ticker.FuncFormatter(lambda x, pos: '{:.2f}'.format(x / 10 ** 9) + 'B')
53 |
54 | h, l = g.axes.flatten()[0].get_legend_handles_labels()
55 | for hi in h:
56 | hi.set_markeredgecolor('white')
57 | g.axes.flatten()[0].legend_.remove()
58 | g.fig.legend(h, l, ncol=2, bbox_to_anchor=(0.53 ,0.53),
59 | fancybox=False, columnspacing=0, framealpha=1, handlelength=1.2)
60 |
61 | for ax in g.axes.flatten():
62 | ax.yaxis.set_minor_locator(ticker.AutoMinorLocator())
63 | ax.set_ylim(bottom=40, top=90)
64 | ax.set_xscale('symlog')
65 | ax.set_xlim(left=0.04 * 10 ** 9, right=2 * 10 ** 9)
66 |
67 | ax.xaxis.set_minor_locator(ticker.SymmetricalLogLocator(base=10, linthresh=2, subs=[1.5, 2,3,4,5,6,8]))
68 | ax.xaxis.set_minor_formatter(b_formatter)
69 | ax.grid(which='minor', linestyle='--', color='#eeeeee')
70 |
71 | ax.xaxis.set_major_formatter(b_formatter)
72 | ax.tick_params(axis="x", which="both", rotation=90)
73 |
74 | plt.savefig(args.output, bbox_inches='tight')
75 |
76 |
77 | def bd(args):
78 | exps = expman.gather(args.run).filter(args.filter)
79 | blink_metrics = exps.collect('test_pred/all_blink_roc_metrics.csv')
80 | blink_metrics = blink_metrics.iloc[3::4].rename({'0': 'auc'}, axis=1)
81 | aucs = blink_metrics.auc.values
82 | print(f'{aucs.mean()} +- {aucs.std()}')
83 |
84 |
85 | def dice_fps(args):
86 | exps = expman.gather(args.run).filter(args.filter)
87 |
88 | mask_metrics = exps.collect('test_pred/mask_metrics.csv')
89 | mask_metrics = mask_metrics.groupby('exp_name').dice.max()
90 |
91 | time_metrics = exps.collect('timings.csv')
92 | time_metrics = time_metrics.rename({'Unnamed: 0': 'metrics', '0':'value'}, axis=1)
93 | time_metrics = time_metrics.pivot_table(index='exp_name', columns='metrics', values='value')
94 |
95 | flops_nparams = exps.collect('flops_nparams.csv')
96 | flops_nparams = flops_nparams.set_index('exp_name')[['flops','nparams']]
97 |
98 | table = pd.concat((time_metrics, mask_metrics, flops_nparams), axis=1)[['dice', 'fps', 'throughput', 'flops', 'nparams']]
99 | table['dice'] = table.dice.map('{:.1%}'.format)
100 | table['fps'] = table.fps.map('{:.1f}'.format)
101 | table['throughput'] = (table.throughput*1000).map('{:.1f}ms'.format)
102 | table['flops'] = (table.flops / 10**9).map('{:.1f}G'.format)
103 | table['nparams'] = (table.nparams / 10**6).map('{:.2f}M'.format)
104 | print(table)
105 |
106 |
107 | def metrics(args):
108 | exps = expman.gather(args.run).filter(args.filter)
109 | mask_metrics = exps.collect('test_pred/mask_metrics.csv')
110 | sns.lineplot(data=mask_metrics, x='thr', y='dice', hue='conv_type', size='grow_factor', style='num_filters')
111 | plt.savefig(args.output)
112 |
113 |
114 | def log(args):
115 | exps = expman.gather(args.run).filter(args.filter)
116 | with PdfPages(args.output) as pdf:
117 | for exp_name, exp in sorted(exps.items()):
118 | print(exp_name)
119 | log = pd.read_csv(exp.path_to('log.csv'), index_col='epoch')
120 | train_cols = [c for c in log.columns if 'val' not in c]
121 | val_cols = [c for c in log.columns if 'val' in c]
122 |
123 | test_images = glob(os.path.join(exp.path_to('test_pred'), '*_samples.png'))
124 |
125 | fig = plt.figure(figsize=(14, 10))
126 | fig_shape = (2, 2) if test_images else (2, 1)
127 | ax1 = plt.subplot2grid(fig_shape, (0, 0))
128 | ax2 = plt.subplot2grid(fig_shape, (1, 0))
129 |
130 | log[train_cols].plot(ax=ax1)
131 | log[val_cols].plot(ax=ax2)
132 | ax1.legend(loc='center right', bbox_to_anchor=(-0.05, 0.5))
133 | ax2.legend(loc='center right', bbox_to_anchor=(-0.05, 0.5))
134 | ax2.set_ylim((0, 1))
135 |
136 | if test_images:
137 | test_images = sorted(test_images)
138 | test_images = list(map(imread, test_images))
139 | max_w = max(i.shape[1] for i in test_images)
140 | pads = [((0,0), (0, max_w - i.shape[1]), (0, 0)) for i in test_images]
141 | test_images = np.concatenate([np.pad(i, pad) for i, pad in zip(test_images, pads)], axis=0)
142 |
143 | ax3 = plt.subplot2grid(fig_shape, (0, 1), rowspan=2)
144 | ax3.imshow(test_images)
145 | ax3.set_axis_off()
146 |
147 | log_plot_file = exp.path_to('log_plot.pdf')
148 | plt.suptitle(exp_name)
149 | plt.savefig(log_plot_file, bbox_inches='tight')
150 | pdf.savefig(fig, bbox_inches='tight')
151 | plt.close()
152 |
153 |
154 | if __name__ == '__main__':
155 | parser = argparse.ArgumentParser(description='Show stuff')
156 | parser.add_argument('-f', '--filter', default={}, type=expman.exp_filter)
157 | subparsers = parser.add_subparsers()
158 |
159 | parser_log = subparsers.add_parser('log')
160 | parser_log.add_argument('run', default='runs/')
161 | parser_log.add_argument('-o', '--output', default='log_summary.pdf')
162 | parser_log.set_defaults(func=log)
163 |
164 | parser_metrics = subparsers.add_parser('metrics')
165 | parser_metrics.add_argument('run', default='runs/')
166 | parser_metrics.add_argument('-o', '--output', default='mask_metrics_summary.pdf')
167 | parser_metrics.set_defaults(func=metrics)
168 |
169 | parser_ee = subparsers.add_parser('ee')
170 | parser_ee.add_argument('run', default='runs/')
171 | parser_ee.add_argument('-o', '--output', default='ee_summary.pdf')
172 | parser_ee.set_defaults(func=ee)
173 |
174 | parser_bd = subparsers.add_parser('bd')
175 | parser_bd.add_argument('run', default='runs/')
176 | parser_bd.set_defaults(func=bd)
177 |
178 | parser_dice_fps = subparsers.add_parser('dice-fps')
179 | parser_dice_fps.add_argument('run', default='runs/')
180 | parser_dice_fps.set_defaults(func=dice_fps)
181 |
182 | args = parser.parse_args()
183 | args.func(args)
184 |
--------------------------------------------------------------------------------
/evaluate.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """ MEye: Semantic Segmentation """
3 |
4 | import argparse
5 | import os
6 | os.sys.path += ['expman', 'models/deeplab']
7 | import expman
8 |
9 | import matplotlib
10 | matplotlib.use('Agg')
11 | import matplotlib.pyplot as plt
12 |
13 | import numpy as np
14 | import pandas as pd
15 | import tensorflow as tf
16 | from tensorflow.keras import backend as K
17 | from tensorflow.keras.models import load_model
18 | from sklearn.model_selection import train_test_split
19 | from sklearn.metrics import classification_report, roc_curve, auc, precision_recall_curve, average_precision_score
20 | from adabelief_tf import AdaBeliefOptimizer
21 | from glob import glob
22 | from tqdm import tqdm
23 | from PIL import Image
24 |
25 | from deeplabv3p.models.deeplabv3p_mobilenetv3 import hard_swish
26 | from dataloader import get_loader, load_datasets
27 | from utils import visualize, visualizable
28 |
29 |
30 | def iou_coef(y_true, y_pred, smooth=0.001, thr=None):
31 | y_pred = K.cast(y_pred > thr, 'float32') if thr is not None else y_pred
32 | intersection = K.sum(K.abs(y_true * y_pred), axis=[1, 2, 3])
33 | union = K.sum(y_true, [1, 2, 3]) + K.sum(y_pred, [1, 2, 3]) - intersection
34 | iou = K.mean((intersection + smooth) / (union + smooth), axis=0)
35 | return iou
36 |
37 |
38 | def dice_coef(y_true, y_pred, smooth=0.001, thr=None):
39 | y_pred = K.cast(y_pred > thr, 'float32') if thr is not None else y_pred
40 | intersection = K.sum(y_true * y_pred, axis=[1, 2, 3])
41 | union = K.sum(y_true, axis=[1, 2, 3]) + K.sum(y_pred, axis=[1, 2, 3])
42 | dice = K.mean((2. * intersection + smooth) / (union + smooth), axis=0)
43 | return dice
44 |
45 |
46 | def _filter_by_closeness(a, eps=10e-3):
47 | keep = []
48 | prev = np.array([-1, -1])
49 | for row in a.drop('thr', axis=1).values:
50 | if (np.abs(prev - row) > eps).any():
51 | keep.append(True)
52 | prev = row
53 | else:
54 | keep.append(False)
55 | return a[keep]
56 |
57 |
58 | def _weighted_roc_pr(y_true, y_scores, label, outdir, simplify=False):
59 | npos = y_true.sum()
60 | nneg = len(y_true) - npos
61 | pos_weight = nneg / npos
62 | print(label, 'Tot:', len(y_true), 'P:', npos, 'N:', nneg, 'N/P:', pos_weight)
63 | sample_weight = np.where(y_true, pos_weight, 1)
64 |
65 | fpr, tpr, thr = roc_curve(y_true, y_scores, sample_weight=sample_weight)
66 | auc_score = auc(fpr, tpr)
67 | print(label, 'AuROC:', auc_score)
68 |
69 | roc_metrics = pd.Series({'npos': npos, 'nneg': nneg, 'nneg_over_npos': pos_weight, 'roc_auc': auc_score})
70 | roc_metrics_file = os.path.join(outdir, '{}_roc_metrics.csv'.format(label))
71 | roc_metrics.to_csv(roc_metrics_file, index=False)
72 |
73 | roc = pd.DataFrame({'fpr': fpr, 'tpr': tpr, 'thr': thr})
74 | if simplify:
75 | full_roc_file = os.path.join(outdir, '{}_roc_curve_full.csv.gz'.format(label))
76 | roc.to_csv(full_roc_file, index=False)
77 | roc = _filter_by_closeness(roc)
78 |
79 | roc_file = os.path.join(outdir, '{}_roc_curve.csv'.format(label))
80 | roc.to_csv(roc_file, index=False)
81 |
82 | roc.plot(x='fpr', y='tpr', xlim=(0, 1), ylim=(0, 1))
83 | roc_plot_file = os.path.join(outdir, '{}_roc.pdf'.format(label))
84 | plt.savefig(roc_plot_file)
85 | plt.close()
86 |
87 | precision, recall, thr = precision_recall_curve(y_true, y_scores, sample_weight=sample_weight)
88 | f1_score = 2 * precision * recall / (precision + recall)
89 | pr_auc = auc(recall, precision)
90 |
91 | pr_metrics = pd.Series({'npos': npos, 'nneg': nneg, 'nneg_over_npos': pos_weight, 'pr_auc': pr_auc})
92 | pr_metrics_file = os.path.join(outdir, '{}_pr_metrics.csv'.format(label))
93 | pr_metrics.to_csv(pr_metrics_file, index=False)
94 |
95 | thr = np.append(thr, [thr[-1]])
96 | pr = pd.DataFrame({'precision': precision, 'recall': recall, 'f1_score': f1_score, 'thr': thr})
97 | if simplify:
98 | full_pr_file = os.path.join(outdir, '{}_pr_curve_full.csv.gz'.format(label))
99 | pr.to_csv(full_pr_file, index=False)
100 | pr = _filter_by_closeness(pr)
101 |
102 | pr_file = os.path.join(outdir, '{}_pr_curve.csv'.format(label))
103 | pr.to_csv(pr_file, index=False)
104 |
105 | pr.plot(x='recall', y='precision', xlim=(0, 1), ylim=(0, 1))
106 | pr_plot_file = os.path.join(outdir, '{}_pr.pdf'.format(label))
107 | plt.savefig(pr_plot_file)
108 | plt.close()
109 |
110 | print(label, 'AuPR:', pr_auc, 'AvgP:', average_precision_score(y_true, y_scores, sample_weight=sample_weight))
111 |
112 |
113 | # https://github.com/tensorflow/tensorflow/issues/32809#issuecomment-768977280
114 | from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2_as_graph
115 | def get_flops(model):
116 | concrete = tf.function(lambda inputs: model(inputs))
117 | concrete_func = concrete.get_concrete_function(
118 | [tf.TensorSpec([1, *inputs.shape[1:]]) for inputs in model.inputs])
119 | frozen_func, graph_def = convert_variables_to_constants_v2_as_graph(concrete_func)
120 | with tf.Graph().as_default() as graph:
121 | tf.graph_util.import_graph_def(graph_def, name='')
122 | run_meta = tf.compat.v1.RunMetadata()
123 | opts = tf.compat.v1.profiler.ProfileOptionBuilder.float_operation()
124 | flops = tf.compat.v1.profiler.profile(graph=graph, run_meta=run_meta, cmd="op", options=opts)
125 |
126 | tf.compat.v1.reset_default_graph()
127 | return flops.total_float_ops
128 |
129 |
130 | def evaluate(exp, force=False):
131 |
132 | ckpt_path = exp.path_to('best_model.h5')
133 |
134 | custom_objects = {'AdaBeliefOptimizer': AdaBeliefOptimizer, 'iou_coef': iou_coef, 'dice_coef': dice_coef, 'hard_swish': hard_swish}
135 | model = tf.keras.models.load_model(ckpt_path, custom_objects=custom_objects)
136 |
137 | # get flops
138 | flop_params_path = exp.path_to('flops_nparams.csv')
139 | if force or not os.path.exists(flop_params_path):
140 | model.compile()
141 | tf.keras.models.save_model(model, 'tmp_model', overwrite=True, include_optimizer=False)
142 | stripped_model = tf.keras.models.load_model('tmp_model')
143 | flops = get_flops(stripped_model)
144 | nparams = stripped_model.count_params()
145 | del stripped_model
146 | print('FLOPS:', flops)
147 | print('#PARAMS:', nparams)
148 | pd.DataFrame({'flops': flops, 'nparams': nparams}, index=[0]).to_csv(flop_params_path)
149 |
150 | model.compile(loss='binary_crossentropy', metrics={'mask': [iou_coef, dice_coef], 'tags': 'binary_accuracy'})
151 |
152 | params = exp.params
153 | np.random.seed(params.seed)
154 | tf.random.set_seed(params.seed)
155 |
156 | data = load_datasets(params.data)
157 |
158 | # TRAIN/VAL/TEST SPLIT
159 | if params.split == 'subjects': # by SUBJECTS
160 | # val_subjects = (6, 9, 11, 13, 16, 28, 30, 48, 49)
161 | test_subjects = (3, 4, 19, 38, 45, 46, 51, 52)
162 | # train_data = data[~data['sub'].isin(val_subjects + test_subjects)]
163 | # val_data = data[data['sub'].isin(val_subjects)]
164 | test_data = data[data['sub'].isin(test_subjects)]
165 |
166 | elif params.split == 'random': # 70-20-10 %
167 | _, valtest_data = train_test_split(data, test_size=.3, shuffle=True)
168 | _, test_data = train_test_split(valtest_data, test_size=.33)
169 |
170 | x_shape = (params.resolution, params.resolution, 1)
171 | test_gen, test_categories = get_loader(test_data, batch_size=1, x_shape=x_shape)
172 |
173 | prediction_dir = exp.path_to('test_pred')
174 | os.makedirs(prediction_dir, exist_ok=True)
175 |
176 | loss_per_sample = None
177 |
178 | def _get_test_predictions(test_gen, model):
179 | x_masks = []
180 | y_masks, y_tags = [], []
181 | pred_masks, pred_tags = [], []
182 | loss_per_sample = []
183 |
184 | for x, y in tqdm(test_gen, desc='TEST'):
185 | sample_loss = model.test_on_batch(x, reset_metrics=True)
186 | loss_per_sample.append(sample_loss)
187 |
188 | p_mask, p_tags = model.predict_on_batch(x)
189 | pred_masks.append(p_mask)
190 | pred_tags.append(p_tags)
191 | y_masks.append(y['mask'].numpy())
192 | y_tags.append(y['tags'].numpy())
193 | x_masks.append(x.numpy())
194 |
195 | loss_per_sample = np.array(loss_per_sample)
196 | pred_masks = np.concatenate(pred_masks)
197 | pred_tags = np.concatenate(pred_tags)
198 | y_masks = np.concatenate(y_masks)
199 | y_tags = np.concatenate(y_tags)
200 | x_masks = np.concatenate(x_masks)
201 |
202 | return loss_per_sample, x_masks, y_masks, y_tags, pred_masks, pred_tags
203 |
204 |
205 | mask_metrics_path = exp.path_to('test_pred/mask_metrics.csv')
206 | if force or not os.path.exists(mask_metrics_path):
207 | if loss_per_sample is None:
208 | loss_per_sample, x_masks, y_masks, y_tags, pred_masks, pred_tags = _get_test_predictions(test_gen, model)
209 |
210 | thrs = np.linspace(0, 1, 101)
211 | ious = [iou_coef(y_masks, pred_masks, thr=thr).numpy() for thr in thrs]
212 | dices = [dice_coef(y_masks, pred_masks, thr=thr).numpy() for thr in thrs]
213 |
214 | best_thr = max(zip(dices, thrs))[1]
215 |
216 | mask_metrics = pd.DataFrame({'iou': ious, 'dice': dices, 'thr': thrs})
217 | print(mask_metrics.max(axis=0))
218 | mask_metrics.to_csv(mask_metrics_path)
219 | else:
220 | mask_metrics = pd.read_csv(mask_metrics_path, index_col=0)
221 | best_thr = mask_metrics.loc[mask_metrics.dice.idxmax(), 'thr']
222 |
223 | if force:
224 | if loss_per_sample is None:
225 | loss_per_sample, x_masks, y_masks, y_tags, pred_masks, pred_tags = _get_test_predictions(test_gen, model)
226 | # _weighted_roc_pr(y_masks.ravel(), pred_masks.ravel(), 'all_pupil', prediction_dir, simplify=True)
227 | _weighted_roc_pr(y_tags[:, 0], pred_tags[:, 0], 'all_eye', prediction_dir)
228 | _weighted_roc_pr(y_tags[:, 1], pred_tags[:, 1], 'all_blink', prediction_dir)
229 |
230 | filenames = ('top_samples.png', 'bottom_samples.png', 'random_samples.png')
231 | if force or any(not os.path.exists(os.path.join(prediction_dir, f)) for f in filenames):
232 | if loss_per_sample is None:
233 | loss_per_sample, x_masks, y_masks, y_tags, pred_masks, pred_tags = _get_test_predictions(test_gen, model)
234 |
235 | k = 5
236 | best_selector = []
237 | worst_selector = []
238 | random_selector = []
239 |
240 | idx = np.arange(len(test_data))
241 | for cat in np.unique(test_categories):
242 | cat_outdir = os.path.join(prediction_dir, cat)
243 | os.makedirs(cat_outdir, exist_ok=True)
244 |
245 | selector = test_categories == cat
246 | # _weighted_roc_pr(y_masks[selector].ravel(), pred_masks[selector].ravel(), '{}_pupil'.format(cat), cat_outdir, simplify=True)
247 | _weighted_roc_pr(y_tags[selector, 0], pred_tags[selector, 0], '{}_eye'.format(cat), cat_outdir)
248 | _weighted_roc_pr(y_tags[selector, 1], pred_tags[selector, 1], '{}_blink'.format(cat), cat_outdir)
249 |
250 | cat_losses = loss_per_sample[selector, 1]
251 | rank = cat_losses.argsort()
252 | topk, bottomk = rank[:k], rank[-k:]
253 |
254 | best_selector += idx[selector][topk].tolist()
255 | worst_selector += idx[selector][bottomk].tolist()
256 | random_selector += np.random.choice(idx[selector], k, replace=False).tolist()
257 |
258 | # topk-bottomk images
259 | selectors = (best_selector, worst_selector, random_selector)
260 | for selector, outfile in zip(selectors, filenames):
261 | combined_m = np.concatenate((pred_masks[selector], y_masks[selector]), axis=-1)[:, :, :, ::-1]
262 | combined_t = np.concatenate((pred_tags[selector], y_tags[selector]), axis=-1)
263 | combined_y = (combined_m, combined_t)
264 | out = os.path.join(prediction_dir, outfile)
265 | visualize(x_masks[selector], combined_y, out=out, thr=best_thr, n_cols=k, width=10)
266 |
267 | for i, (xi, yi_mask) in enumerate(zip(x_masks[selector], combined_m)):
268 | img = visualizable(xi, yi_mask, thr=best_thr)
269 | img = (img * 255).astype(np.uint8)
270 | out = os.path.join(prediction_dir, outfile[:-4])
271 | os.makedirs(out, exist_ok=True)
272 | out = os.path.join(out, f'{i}.png')
273 | Image.fromarray(img).save(out)
274 |
275 |
276 | def main(args):
277 | for exp in expman.gather(args.run).filter(args.filter):
278 | print(exp)
279 | evaluate(exp, force=args.force)
280 |
281 |
282 | if __name__ == '__main__':
283 | parser = argparse.ArgumentParser(description='Evaluate Run')
284 | # data params
285 | parser.add_argument('run', help='Run(s) directory')
286 | parser.add_argument('-f', '--filter', default={}, type=expman.exp_filter)
287 | parser.add_argument('--force', default=False, action='store_true', help='Force metrics recomputation')
288 |
289 | args = parser.parse_args()
290 | main(args)
291 |
--------------------------------------------------------------------------------
/matlab/Meye.m:
--------------------------------------------------------------------------------
1 | classdef Meye
2 |
3 | properties (Access=private)
4 | model
5 | end
6 |
7 |
8 | methods
9 |
10 | % CONSTRUCTOR
11 | %------------------------------------------------------------------
12 | function self = Meye(modelPath)
13 | % Class constructor
14 | arguments
15 | modelPath char {mustBeText}
16 | end
17 |
18 | % Change the current directory to the directory where the
19 | % original class is, so that the package with the custom layers
20 | % is created there
21 | classPath = getClassPath(self);
22 | oldFolder = cd(classPath);
23 | % Import the model saved as ONNX
24 | self.model = importONNXNetwork(modelPath, ...
25 | 'GenerateCustomLayers',true, ...
26 | 'PackageName','customLayers_meye',...
27 | 'InputDataFormats', 'BSSC',...
28 | 'OutputDataFormats',{'BSSC','BC'});
29 |
30 | % Manually change the "nearest" option to "linear" inside of
31 | % the automatically generated custom layers. This is necessary
32 | % due to the fact that MATLAB still does not support the proper
33 | % translation between ONNX layers and DLtoolbox layers
34 | self.nearest2Linear([classPath filesep '+customLayers_meye'])
35 |
36 | % Go back to the old current folder
37 | cd(oldFolder)
38 | end
39 |
40 |
41 | % PREDICTION OF SINGLE IMAGES
42 | %------------------------------------------------------------------
43 | function [pupilMask, eyeProb, blinkProb] = predictImage(self, inputImage, options)
44 | % Predicts pupil location on a single image
45 | arguments
46 | self
47 | inputImage
48 | options.roiPos = []
49 | options.threshold = []
50 | end
51 |
52 | roiPos = options.roiPos;
53 |
54 | % Convert the image to grayscale if RGB
55 | if size(inputImage,3) > 1
56 | inputImage = im2gray(inputImage);
57 | end
58 |
59 | % Crop the frame to the desired ROI
60 | if ~isempty(roiPos)
61 | crop = inputImage(roiPos(2):roiPos(2)+roiPos(4)-1,...
62 | roiPos(1):roiPos(1)+roiPos(3)-1);
63 | else
64 | crop = inputImage;
65 | end
66 |
67 | % Preprocessing
68 | img = double(imresize(crop,[128 128]));
69 | img = img / max(img,[],'all');
70 |
71 | % Do the prediction
72 | [rawMask, info] = predict(self.model, img);
73 | eyeProb = info(1);
74 | blinkProb = info(2);
75 |
76 | % Reinsert the cropped prediction in the frame
77 | if ~isempty(roiPos)
78 | pupilMask = zeros(size(inputImage));
79 | pupilMask(roiPos(2):roiPos(2)+roiPos(4)-1,...
80 | roiPos(1):roiPos(1)+roiPos(3)-1) = imresize(rawMask, [roiPos(4), roiPos(3)],"bilinear");
81 | else
82 | pupilMask = imresize(rawMask,size(inputImage),"bilinear");
83 | end
84 |
85 | % Apply a threshold to the image if requested
86 | if ~isempty(options.threshold)
87 | pupilMask = pupilMask > options.threshold;
88 | end
89 |
90 | end
91 |
92 |
93 | % PREDICT A MOVIE AND GET A TABLE WITH THE RESULTS
94 | %------------------------------------------------------------------
95 | function tab = predictMovie(self, moviePath, options)
96 | % Predict an entire video file and returns a results Table
97 | %
98 | % tab = predictMovie(moviePath, name-value)
99 | %
100 | % INPUT(S)
101 | % - moviePath: (char/string) Full path of a video file.
102 | % - name-value pairs
103 | % - roiPos: [x,y,width,height] 4-elements vector defining a
104 | % rectangle containing the eye. Works best if width and
105 | % height are similar. If empty, a prediction will be done on
106 | % a full frame(Default: []).
107 | % - threshold: [0-1] The pupil prediction is binarized based
108 | % on a threshold value to measure pupil size. (Default:0.4)
109 | %
110 | % OUTPUT(S)
111 | % - tab: a MATLAB table containing data of the analyzed video
112 |
113 | arguments
114 | self
115 | moviePath char {mustBeText}
116 | options.roiPos double = []
117 | options.threshold = 0.4;
118 | end
119 |
120 | % Initialize a video reader
121 | v = VideoReader(moviePath);
122 | totFrames = v.NumFrames;
123 |
124 | % Initialize Variables
125 | frameN = zeros(totFrames,1,'double');
126 | frameTime = zeros(totFrames,1,'double');
127 | binaryMask = cell(totFrames,1);
128 | pupilArea = zeros(totFrames,1,'double');
129 | isEye = zeros(totFrames,1,'double');
130 | isBlink = zeros(totFrames,1,'double');
131 |
132 | tic
133 | for i = 1:totFrames
134 | % Progress report
135 | if toc>10
136 | fprintf('%.1f%% - Processing frame (%u/%u)\n', (i/totFrames)*100 , i, totFrames)
137 | tic
138 | end
139 |
140 | % Read a frame and make its prediction
141 | frame = read(v, i, 'native');
142 | [pupilMask, eyeProb, blinkProb] = self.predictImage(frame, roiPos=options.roiPos,...
143 | threshold=options.threshold);
144 |
145 | % Save results for this frame
146 | frameN(i) = i;
147 | frameTime(i) = v.CurrentTime;
148 | binaryMask{i} = pupilMask > options.threshold;
149 | pupilArea(i) = sum(binaryMask{i},"all");
150 | isEye(i) = eyeProb;
151 | isBlink(i) = blinkProb;
152 | end
153 | % Save all the results in a final table
154 | tab = table(frameN,frameTime,binaryMask,pupilArea,isEye,isBlink);
155 | end
156 |
157 |
158 |
159 | % PREVIEW OF A PREDICTED MOVIE
160 | %------------------------------------------------------------------
161 | function predictMovie_Preview(self, moviePath, options)
162 | % Displays a live-preview of prediction for a video file
163 |
164 | arguments
165 | self
166 | moviePath char {mustBeText}
167 | options.roiPos double = []
168 | options.threshold double = []
169 | end
170 | roiPos = options.roiPos;
171 |
172 |
173 | % Initialize a video reader
174 | v = VideoReader(moviePath);
175 | % Initialize images to show
176 | blankImg = zeros(v.Height, v.Width, 'uint8');
177 | cyanColor = cat(3, blankImg, blankImg+255, blankImg+255);
178 | pupilTransparency = blankImg;
179 |
180 | % Create a figure for the preview
181 | figHandle = figure(...
182 | 'Name','MEYE video preview',...
183 | 'NumberTitle','off',...
184 | 'ToolBar','none',...
185 | 'MenuBar','none', ...
186 | 'Color',[.1, .1, .1]);
187 |
188 | ax = axes('Parent',figHandle,...
189 | 'Units','normalized',...
190 | 'Position',[0 0 1 .94]);
191 |
192 | imHandle = imshow(blankImg,'Parent',ax);
193 | hold on
194 | cyanHandle = imshow(cyanColor,'Parent',ax);
195 | cyanHandle.AlphaData = pupilTransparency;
196 | rect = rectangle('LineWidth',1.5, 'LineStyle','-.','EdgeColor',[1,0,0],...
197 | 'Parent',ax,'Position',[0,0,0,0]);
198 | hold off
199 | title(ax,'MEYE Video Preview', 'Color',[1,1,1])
200 |
201 | % Movie-Showing loop
202 | while exist("figHandle","var") && ishandle(figHandle) && hasFrame(v)
203 | try
204 | tic
205 | frame = readFrame(v);
206 |
207 | % Actually do the prediction
208 | [pupilMask, eyeProb, blinkProb] = self.predictImage(frame, roiPos=roiPos,...
209 | threshold=options.threshold);
210 |
211 | % Update graphic elements
212 | imHandle.CData = frame;
213 | cyanHandle.AlphaData = imresize(pupilMask, [v.Height, v.Width]);
214 | if ~isempty(roiPos)
215 | rect.Position = roiPos;
216 | end
217 | titStr = sprintf('Eye: %.2f%% - Blink:%.2f%% - FPS:%.1f',...
218 | eyeProb*100, blinkProb*100, 1/toc);
219 | ax.Title.String = titStr;
220 | drawnow
221 | catch ME
222 | warning(ME.message)
223 | close(figHandle)
224 | end
225 | end
226 | disp('Stop preview.')
227 | end
228 |
229 |
230 | end
231 |
232 |
233 | %------------------------------------------------------------------
234 | %------------------------------------------------------------------
235 | % INTERNAL FUNCTIONS
236 | %------------------------------------------------------------------
237 | %------------------------------------------------------------------
238 | methods(Access=private)
239 | %------------------------------------------------------------------
240 | function path = getClassPath(~)
241 | % Returns the full path of where the class file is
242 |
243 | fullPath = mfilename('fullpath');
244 | [path,~,~] = fileparts(fullPath);
245 | end
246 |
247 | %------------------------------------------------------------------
248 | function [fplist,fnlist] = listfiles(~, folderpath, token)
249 | listing = dir(folderpath);
250 | index = 0;
251 | fplist = {};
252 | fnlist = {};
253 | for i = 1:size(listing,1)
254 | s = listing(i).name;
255 | if contains(s,token)
256 | index = index+1;
257 | fplist{index} = [folderpath filesep s];
258 | fnlist{index} = s;
259 | end
260 | end
261 | end
262 |
263 | % nearest2Linear
264 | %------------------------------------------------------------------
265 | function nearest2Linear(self, inputPath)
266 | fP = self.listfiles(inputPath, 'Shape_To_Upsample');
267 |
268 | foundFileToChange = false;
269 | beforePatter = '"half_pixel", "nearest",';
270 | afterPattern = '"half_pixel", "linear",';
271 | for i = 1:length(fP)
272 |
273 | % Get the content of the file
274 | fID = fopen(fP{i}, 'r');
275 | f = fread(fID,'*char')';
276 | fclose(fID);
277 |
278 | % Send a verbose warning the first time we are manually
279 | % correcting the upsampling layers bug
280 | if ~foundFileToChange && contains(f,beforePatter)
281 | foundFileToChange = true;
282 | msg = ['This is a message from MEYE developers.\n' ...
283 | 'In the current release of the Deep Learning Toolbox ' ...
284 | 'MATLAB does not translate well all the layers in the ' ...
285 | 'ONNX network to native MATLAB layers. In particular the ' ...
286 | 'automatically generated custom layers that have to do ' ...
287 | 'with UPSAMPLING are generated with the ''nearest'' instead of ' ...
288 | 'the ''linear'' mode.\nWe automatically correct for this bug when you ' ...
289 | 'instantiate a Meye object (henche this warning).\nEverything should work fine, ' ...
290 | 'and we hope that in future MATLAB releases this hack wont be ' ...
291 | 'needed anymore.\n' ...
292 | 'If you find bugs or performance issues, please let us know ' ...
293 | 'with an issue ' ...
294 | 'HERE.'];
295 | warning(sprintf(msg))
296 | end
297 |
298 | % Replace the 'nearest' option with 'linear'
299 | newF = strrep(f, beforePatter, afterPattern);
300 |
301 | % Save the file back in its original location
302 | fID = fopen(fP{i}, 'w');
303 | fprintf(fID,'%s',newF);
304 | fclose(fID);
305 | end
306 | end
307 | end
308 | end
309 |
310 |
311 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------