plot_vuln.py 4.17 KB
Newer Older
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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
import os
import bob.measure
import matplotlib.pyplot as plt
import numpy
from bob.bio.base.score.load import load_score
from bob.pad.base.script.vuln_figure import _iapmr_plot
from matplotlib import gridspec

np = numpy


def return_scores(scores):

    print("in function return_scores")
    gen = scores[scores['real_id'] == scores['claimed_id']]['score']

    makeup = scores[scores['real_id'] == 'makeup']['score']

    return np.ascontiguousarray(gen), np.ascontiguousarray(makeup)


def main():

	# import ipdb; ipdb.set_trace()

    directory = '/idiap/user/zmostaani/experiments/batl/aim_result/'
    method = 'aim_vuln/grandtest/nonorm/'
    filename = 'scores-dev'

    scores = load_score(os.path.join(directory, method, filename))



    gen, makeup = return_scores(scores)
    print("deviding scores")

    plt.style.use('default')

    plt.rcParams['figure.figsize'] = (4, 3)
    plt.rcParams['figure.constrained_layout.use'] = True
    fig = plt.figure()

    gs = gridspec.GridSpec(9, 1, figure=fig)

    ax = plt.gcf().add_subplot(gs[1:8])


    gen_sim = 1 + gen
    makeup_sim = 1 + makeup

    line_props = dict(color="r", alpha=0.3)
    bbox_props = dict(color="b", alpha=0.9)
    flier_props = dict(marker="+", markersize=4, markeredgecolor="g")
    whis_props = [5, 95]
    whisker_props = dict(linestyle='--', dashes=(5, 5))
    median_props = dict(color="r")

    bp = ax.boxplot([gen_sim, makeup_sim], labels=['Genuine', 'Makeup'],
                    patch_artist=False, autorange=True, flierprops=flier_props,
                    boxprops=bbox_props,
                    whiskerprops=whisker_props,
                    medianprops=median_props,
                    whis=whis_props,
                    widths=0.25,
                    )


    top = 1
    bottom = 0
    ax.set_ylim(bottom, top)
    ax.set_aspect(1.5)

    for line in bp['medians']:
        # get position data for median line
        x, y = line.get_xydata()[1]  # top of median line
        # overlay median value
        ax.annotate(f"{y:.2f}", (x, y))

    plt.ylabel("Similarity Scores")
    # plt.xlabel("")
    plt.title("LightCNN FR")
    plt.savefig(os.path.join(directory, 'boxplot-bob-new.png'))

    print("plotting boxplot")
    # plt.xlabel("Normalized count")

    plt.style.use('default')

    plt.rcParams['figure.figsize'] = (4, 3)
    plt.rcParams['figure.constrained_layout.use'] = True

    fig = plt.figure()
    gs = gridspec.GridSpec(9, 1,            figure=fig)

    ax = plt.gcf().add_subplot(gs[1:9])

    title = "LightCNN FR"
    spoof_label = "Makeup"

    # fig, ax = plt.subplots()
    # ax = plt.gcf().add_subplot()

    th = bob.measure.frr_threshold([], gen_sim, 0.1)

    color_scheme = {'genuine': '#2ca02c', 'impostors': '#1f77b4',
                    'line': '#d4257b', 'makeup': '#ff7f0e'}

    alpha_scheme = {'genuine': 0.9, 'impostors': 0.8, 'spoofs': 0.6}
    hatch_scheme = {'genuine': '//', 'impostors': None, 'spoofs': None}

    lines = []

    line = plt.hist(gen_sim, bins=10, color=color_scheme['genuine'],
                    alpha=alpha_scheme['genuine'],
                    hatch=hatch_scheme['genuine'],
                    label="Genuine", density=True)
    lines.append(line[-1][0])

    line = plt.axvline(x=th, ymin=0, ymax=1, linewidth=2,
                       color=color_scheme['line'], linestyle='--',
                       label="FNMR threshold")
    lines.append(line)

    line = plt.hist(makeup_sim, bins=10, color=color_scheme['makeup'],
                    alpha=alpha_scheme['spoofs'],
                    hatch=hatch_scheme['spoofs'],
                    density=True, label=spoof_label)

    lines.append(line[-1][0])

    #     ax.grid(True)
    hs, ls = plt.gca().get_legend_handles_labels()
    # plt.sca(ax)

    ax.grid(True)
    # ax.legend(handletextpad=0.9)

    plt.xlabel("Similarity Scores")
    plt.ylabel("Normalized Count")
    plt.title(title)

    # plt.tight_layout()
    # plt.subplots_adjust(top=0.80)
    by_label = dict(zip(ls, hs))
    fig.legend(by_label.values(), by_label.keys(),
               loc='upper center', ncol=3, framealpha=0.5)

    plt.savefig(os.path.join(directory, 'makeup-FRR-bob-new.png'))

    print("ploting histogram")

if __name__ == "__main__":

    main()