File size: 1,993 Bytes
191195c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import tensorflow as tf
import numpy as np

def get_preprocess_func(config):
    arch = config.MODEL.backbone_arch

    if arch == 'mobilenetv2':
        return tf.keras.applications.mobilenet.preprocess_input
    elif 'resnet' in arch:
        return tf.keras.applications.resnet.preprocess_input
    elif 'eff' in arch:
        return tf.keras.applications.efficientnet.preprocess_input
    elif 'dense' in arch:
        return tf.keras.applications.densenet.preprocess_input
    elif arch == 'xception':
        return tf.keras.applications.xception.preprocess_input
    else:
        raise Exception(f'{arch} is not yet implemented')

def get_unpreprocess_func(config):
    """
    Returns function that processes input to 0-1 float range
    """
    arch = config.MODEL.backbone_arch

    def tensor_to_numpy(x):
        return x.numpy()

    def clip(x):
        return np.clip(x, 0.,1.)

    def none_mode(x):
        x = tensor_to_numpy(x)
        x /= 255.
        return clip(x)

    def caffe_mode(x):
        mean = [103.939, 116.779, 123.68]
        x = tensor_to_numpy(x)
        x[..., 0] += mean[0]
        x[..., 1] += mean[1]
        x[..., 2] += mean[2]
        # 'BGR'->'RGB'
        x = x[..., ::-1]
        x /= 255.
        return clip(x)

    def tf_mode(x):
        x = tensor_to_numpy(x)
        x = (x + 0.5) / 2.0
        return clip(x)

    def torch_mode(x):
        mean=[0.485, 0.456, 0.406]
        std=[0.229, 0.224, 0.225]
        x = tensor_to_numpy(x)
        x[..., 0] = (x[..., 0] * std[0]) + mean[0]
        x[..., 1] = (x[..., 1] * std[1]) + mean[1]
        x[..., 2] = (x[..., 2] * std[2]) + mean[2]
        return clip(x)

    if arch == 'mobilenetv2':
        return tf_mode
    elif 'resnet' in arch:
        return caffe_mode
    elif 'eff' in arch:
        return none_mode
    elif 'dense' in arch:
        return torch_mode
    elif arch == 'xception':
        return tf_mode
    else:
        raise Exception(f'{arch} is not yet implemented')