seekthermal_PAD.py 25 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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
'''
Created on Nov 10, 2017

@author: sbhatta
'''


import os, sys
import time
import argparse
import numpy as np
from matplotlib import pyplot as P
from PIL import Image
from skimage import transform

import bob.io.base
import bob.io.video
from bob.ip.draw import box, cross, plus
import bob.ip.facedetect
import bob.learn.linear
# import antispoofing.utils.db as bobdb
import bob.learn.em
import bob.measure
# import bob.learn.libsvm
# from sklearn.metrics.cluster import adjusted_mutual_info_score

from cv2 import CascadeClassifier
#from bob.bio.face.preprocessor import HistogramEqualization
#import MyBobLib as mbl
import math
import bob.io.image
import bob.io.video
import bob.ip.color
import bob.ip.flandmark

# import bob.bio.face
# 
# # import MSU_IQAFeats as iqa
# import MSU_MaskedIQAFeats as iqa
# import tanSpecularHighlights as tsh

import matplotlib
from matplotlib import pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

#lastFaceBBox = None        #global var. storing the face-bounding-box used in previous frame



'''
'''
def plotBoundingboxOnImage(grayImage, boundingbox):
    boxImg = grayImage.copy()
    y= int(boundingbox[0])
    x= int(boundingbox[1])
    width = int(boundingbox[3]) #-x
    height = int(boundingbox[2])#-y
    topCorner = (y,x)
    print 'topCorner:', topCorner
    print 'size (h,w):', (height, width)
    box(boxImg, topCorner, (height,width), 250)

    return boxImg


'''
return image with landmarks plotted on it.
'''
def plotFaceLandmarksOnImage(grayImage, landmarks):
    lmkImage = np.copy(grayImage)

    darkClr = 120
    brightClr = 240
    lsize=1

    for k in range(len(landmarks)):
        cross(lmkImage, (landmarks[k]).astype(int), lsize, brightClr) # bright-gray key points

    return lmkImage


'''
'''
def imshow(image):
    import matplotlib
    from matplotlib import pyplot as plt
    if len(image.shape)==3:
        #imshow() expects color image in a slightly different format, so first rearrange the 3d data for imshow...
        outImg = image.tolist()
        print len(outImg)
        result = np.dstack((outImg[0], outImg[1]))
        outImg = np.dstack((result, outImg[2]))
        plt.imshow((outImg*255.0).astype(np.uint8)) #[:,:,1], cmap=mpl.cm.gray)
         
    else:
        if(len(image.shape)==2):
            #display gray image.
            plt.imshow(image.astype(np.uint8), cmap=matplotlib.cm.gray)
             
    plt.show()



def load_thermal_data(file_list, output_folder):

    for ic, f in enumerate(file_list):
        datafile_handle = bob.io.base.HDF5File(f, 'r')
        assert datafile_handle.has_group('data'), 'Input file has no -data- group'
        datafile_handle.cd('/data')
        assert datafile_handle.has_group('seek_compact'), 'Input file has no -seek_compact- group'
        datafile_handle.cd('seek_compact')
        assert datafile_handle.has_group('infrared'), 'Input file has no -data/seek_compact/infrared- group'
        datafile_handle.cd('infrared')
        frame_keys = datafile_handle.keys()
        print len(frame_keys)
        
#         print datafile_handle.get_attributes(frame_keys[0])
        
        if not os.path.exists(output_folder):
            os.makedirs(output_folder)
        outfile = os.path.join(output_folder, ((os.path.basename(f)).split('.')[0]+'.npy'))
        print outfile
        img_stream = None
        for ik, k in enumerate(frame_keys):
            img = datafile_handle.read(k)
            img_min = np.amin(img)
            img_max = np.amax(img)
            factor = 255.0/(img_max-img_min)
            corr_img = ((img.astype(np.float64)-img_min)*factor).astype(np.uint8)
            if ik==0:
                img_stream = corr_img
            else:
                img_stream = np.dstack((img_stream, corr_img))
            
        np.save(outfile, img_stream)
#         bob.io.image.imshow(corr_img)
        print ic
        
#         filename = '/idiap/temp/sbhatta/work/test_thermalImg.png'
#         bob.io.base.save(corr_img, filename, create_directories=False)
#         assert 0, 'stop!'


def load_rgb_data(file_list, output_folder):

    for ic, f in enumerate(file_list):
        datafile_handle = bob.io.base.HDF5File(f, 'r')
        assert datafile_handle.has_group('data'), 'Input file has no -data- group'
        datafile_handle.cd('/data')
        assert datafile_handle.has_group('sr300'), 'Input file has no -seek_compact- group'
        datafile_handle.cd('sr300')
        assert datafile_handle.has_group('color'), 'Input file has no -data/seek_compact/infrared- group'
        datafile_handle.cd('color')
        frame_keys = datafile_handle.keys()
        print len(frame_keys)
        
#         print datafile_handle.get_attributes(frame_keys[0])
        
        if not os.path.exists(output_folder):
            os.makedirs(output_folder)
        outfile = os.path.join(output_folder, ((os.path.basename(f)).split('.')[0]+'.npy'))
        print outfile
        img_stream = []
#         for ik, k in enumerate(frame_keys):
        for ik in range(10):
            k = frame_keys[ik]
            img = datafile_handle.read(k)
            img_stream.append(img)
        
        video = np.concatenate([arr[np.newaxis] for arr in img_stream])

        np.save(outfile, video)
        print ic


'''
'''
def resize_rgb_image(inpVid, outWidth):
    frame_list = []
    inHeight = inpVid.shape[2]
#     print inpVid.shape
    for n in range(inpVid.shape[0]):
        frame_img = Image.fromarray(inpVid[n])
#         print frame_img.size
#         assert 0, 'stop!'
        wpercent = (float(outWidth)/float(inHeight))
        hsize = int((float(frame_img.size[1])*float(wpercent)))
        
#         img = img.resize((outWidth, hsize), Image.ANTIALIAS)
        img = frame_img.resize((outWidth,hsize), Image.ANTIALIAS)

        img=img.convert('L') #makes it greyscale
#         img.show()
#         assert 0, 'stop'
        frame_list.append(np.asarray(img))

    gray_vid = np.concatenate([arr[np.newaxis] for arr in frame_list])

    return gray_vid

'''
'''
def sr300_rgb_to_gray(folder):
    ''' folder should be a string; either 'bonafide' or 'attack' '''
    outWidth = 640
#     outHeight= 480
    data_root = '/idiap/temp/sbhatta/work/3DMask_Data/'
    rgb_data_path = os.path.join(data_root, 'SR300_3')
    data_folder = os.path.join(rgb_data_path, folder)
#     data_folder = os.path.join(rgb_data_path, 'bonafide')
    output_folder = os.path.join(data_root,('SR300_3/gray/'+folder))
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)
        
    rgb_files = os.listdir(data_folder)
    for i, f in enumerate(rgb_files):
        outfile = os.path.join(output_folder, ((os.path.basename(f)).split('.')[0]+'_gray.npy'))
        
        frame_array = np.load(os.path.join(data_folder, f))
        print frame_array.shape
        gray_vid = resize_rgb_image(frame_array, outWidth)
        
        print gray_vid.shape
        print outfile
        np.save(outfile, gray_vid)


'''
returns the following initialized objects: 
 :return: cc: a trained cascade classifier for frontal face rec., 
 :return: fl: a face-landmark-detector
 :return: fn: a face-normalizer (used to generate a cropped-normalized-face)
'''
def initFaceExtractor():
    CI_HEIGHT = 120 # cropped_image_height
    CI_WIDTH = CI_HEIGHT * 4 // 4 # cropped_image_width
    RIGHT_EYE_NORM = (CI_HEIGHT // 4, CI_WIDTH // 4 )
    LEFT_EYE_NORM = (CI_HEIGHT // 4, CI_WIDTH // 4 * 3)
    
    #parameters that conform with MSU-TIFS2015 experiments
    CI_HEIGHT = 144
    CI_WIDTH = 120
    RIGHT_EYE_NORM = (CI_HEIGHT // 4, CI_WIDTH // 4 )
    LEFT_EYE_NORM = (CI_HEIGHT // 4, CI_WIDTH // 4 * 3)
    
    #normRightEye = (20, 25)
    #normLeftEye = (20, 75)
    fn = bob.ip.base.FaceEyesNorm([CI_HEIGHT, CI_WIDTH], RIGHT_EYE_NORM, LEFT_EYE_NORM)
    # OR, define the face-crop preprocessor
    #fn = bob.bio.face.preprocessor.FaceCrop(
    #                                        cropped_image_size = (CI_HEIGHT, CI_WIDTH),
    #                                        cropped_positions = {'leye' : LEFT_EYE_NORM, 'reye' : RIGHT_EYE_NORM}
    #                                       )
    fl = bob.ip.flandmark.Flandmark()
    cc = CascadeClassifier(get_file('haarcascade_frontalface_alt.xml'))
    # /idiap/home/sbhatta/work/downloaded_code/EulerianMagnification/EVM_Matlab/haarcascade_frontalface_alt.xml
    return (cc, fl, fn )


def get_file(f):
    from pkg_resources import resource_filename
    return resource_filename('bob.ip.flandmark', os.path.join('data', f))
        

'''
detect single face in frame and return the bounding-box (position and size)
'''
def detectFace(grayImage, cc, fdflag=0):
    global lastFaceBBox
    
    #step 1: find the face bounding box
    if fdflag == 0:
        #use bob.ip.facedetect to detect faces
        retval = []
        bounding_boxes = None
        qualities = None
        fdResult = bob.ip.facedetect.detect_all_faces(grayImage)
        if fdResult is not None:
            bounding_boxes, qualities = fdResult
        else:
            return retval #return empty keypointset-list if no face-bounding-box was detected
            #select the top candidate for face
        top=1
        bounding_boxes = bounding_boxes[:top]
        qualities = qualities[:top]
        
        #     print bounding_boxes
        a=np.int(np.rint(bounding_boxes[0].topleft[0]))
        b=np.int(np.rint(bounding_boxes[0].topleft[1]))
        c = np.int((np.rint(bounding_boxes[0].bottomright[0]) - a)+1)
        d = np.int((np.rint(bounding_boxes[0].bottomright[1]) - b)+1)
        face_bbx = [a,b,c,d]
# 
#     else:
#         face_bbx = detectFaceOpenCV(grayImage, cc)
    

    return face_bbx, bounding_boxes[0]


def compute_calib_params():
    
#     markers_color       = np.array([[  639.01621245,   829.06611417],
#                                     [ 1116.9561236,    840.35032172],
#                                     [ 1124.14172479,   354.43693199],
#                                     [  640.94149563,   352.4504615 ]])
    markers_color = np.array([[244.5, 430],
                              [431, 430],
                              [244.5, 655.5],
                              [431, 655.5]])

    markers_infrared    = np.array([[ 228.,          347.96117426],
                                    [ 390.79409749,  352.46531649],
                                    [ 394.21976346,  185.96390511],
                                    [ 228.,          186.07019597]])

#     markers_thermal     = np.array([[  56.41123946,  212.71864027],
#                                     [ 240.92947771,  216.83232732],
#                                     [ 243.38550541,   31.07840364],
#                                     [  56.32331049,   29.60347946]])
    markers_thermal     = np.array([[  59.5,  83],
                                    [ 182,  83],
                                    [ 59.5,   222.5],
                                    [ 182,  222.5]])

#     markers_color = np.fliplr(markers_color) #, axis=1)
    markers_infrared = np.fliplr(markers_infrared) #, axis=1)
#     markers_thermal = np.fliplr(markers_thermal) #(markers_thermal, axis=1)

    warp_xform = transform.ProjectiveTransform()
    warp_xform.estimate(markers_color, markers_thermal)
    return warp_xform


def crop_thermal_face(thermal_image, rgb_face_bbox, warp_transform):
    top_left = [rgb_face_bbox[1], rgb_face_bbox[0]]
    top_right = [rgb_face_bbox[1]+rgb_face_bbox[3], rgb_face_bbox[0]]
    bottom_left = [rgb_face_bbox[1], rgb_face_bbox[0]+rgb_face_bbox[2]]
    bottom_right = [rgb_face_bbox[1]+rgb_face_bbox[3], rgb_face_bbox[0]+rgb_face_bbox[2]]
    
#         print(warp_xform(top_left))
#         print(warp_xform(top_right))
#         print(warp_xform(bottom_left))
#         print(warp_xform(bottom_right))
    
    thermal_tl = warp_transform(top_left).astype(np.int)[0]
    thermal_br = warp_transform(bottom_right).astype(np.int)[0]

    thermal_b = thermal_tl[0]
    thermal_a = thermal_tl[1]
    thermal_d = thermal_br[0]-thermal_b
    thermal_c = thermal_br[1]-thermal_a
    thermal_bbx = [thermal_a,thermal_b,thermal_c,thermal_d]
    thermal_face = thermal_image[thermal_a:thermal_a+thermal_c, thermal_b:thermal_b+thermal_d]
    
    return thermal_face, thermal_bbx

'''
'''
def extract_sr300_data(presentation):
    '''presentation: string: either 'bonafide' or 'attack' '''
    data_root = '/idiap/temp/sbhatta/work/3DMask_Data'
    data_path = os.path.join(data_root, ('CVPR_Mask_Data/'+presentation))
    output_folder = os.path.join(data_root, ('SR300_3/'+presentation))
    batl_files = os.listdir(data_path)
    print len(batl_files)
#     print batl_files[0]
#     bf_files = ['E_gen_i0_003', 'E_gen_i1_004', 'E_gen_i2_005', 'E_gen_i3_006', 'F_gen_i0_007', 'F_gen_i1_008', 'F_gen_i2_009', 'F_gen_i3_010']
    bf_list = [os.path.join(data_path, x) for x in batl_files]
#     print bf_list
    print len(bf_list)
 
    load_rgb_data(bf_list, output_folder)
#     assert 0, 'stop'

'''
'''
def extract_seekthermal_data(presentation):
    '''presentation: string: either 'bonafide' or 'attack' '''
    data_root = '/idiap/temp/sbhatta/work/3DMask_Data'
    data_path = os.path.join(data_root, ('CVPR_Mask_Data/'+presentation))
    
    output_folder = os.path.join(data_root, ('SeekThermal/'+presentation))
    batl_files = os.listdir(data_path)
    print len(batl_files)

    bf_list = [os.path.join(data_path, x) for x in batl_files]

    load_thermal_data(bf_list, output_folder)


'''
'''
def extract_thermal_face(presentation):
    #     /idiap/temp/sbhatta/work/3DMask_Data/SeekThermal/bonafide
    data_root = '/idiap/temp/sbhatta/work/3DMask_Data'
    cc, fl, fn = initFaceExtractor() # all detectors initialised
#     presentation='bonafide'
    gray_folder = os.path.join(data_root, ('SR300_3/gray/'+presentation))
    thermal_folder= os.path.join(data_root, ('SeekThermal/'+presentation))
    thermal_face_outfolder = os.path.join(data_root, ('SeekThermal/faces/'+presentation))
    if not os.path.exists(thermal_face_outfolder): os.makedirs(thermal_face_outfolder)
    
    rgb_files = os.listdir(gray_folder)
    thermal_files = os.listdir(thermal_folder)
    warp_xform = compute_calib_params()
    
    for i, f in enumerate(rgb_files):
        print i
        gray_file = os.path.join(gray_folder, f)
        gray_vid = np.load(gray_file) #load a gray-video
        img = gray_vid[0]   # take only first frame
        face_bbx, bbox  = detectFace(img, cc, fdflag=0)
#         print face_bbx
        gray_face = img[face_bbx[0]:face_bbx[0]+face_bbx[2], face_bbx[1]:face_bbx[1]+face_bbx[3]]
        
        fn_components = f.split('_')
        pres_id = fn_components[0]+'_'+fn_components[1]+'_'+fn_components[2]
        thermal_fn = [x for x in thermal_files if pres_id in x]
        print thermal_fn
#         assert len(thermal_fn) == 1, 'Too many thermal-files matching the rgb file'
        
        for t, tf in enumerate(thermal_fn):
            thermal_file = os.path.join(thermal_folder, tf)
            thermal_vid = np.load(thermal_file)
            ofname = thermal_file.split('.')[0]
            thermal_face_list=[]
            for j in range(thermal_vid.shape[2]):
                thermal_frame = thermal_vid[:,:,j]
            
                thermal_face, thermal_bbx = crop_thermal_face(thermal_frame, face_bbx, warp_xform)
                thermal_face_list.append(thermal_face)

            thermal_face_vid = np.concatenate([arr[np.newaxis] for arr in thermal_face_list])
            thermal_face_outfile = os.path.join(thermal_face_outfolder, (ofname+'_face.npy') )
            np.save(thermal_face_outfile, thermal_face_vid)
            print thermal_face_outfile
    

##########


def get_thermal_face_mean(presentation):
    data_root = '/remote/idiap.svm/home.active/sbhatta/disk_temp/work/3DMask_Data'
    thermal_folder = os.path.join(data_root, ('SeekThermal/faces/'+presentation))
    thermal_file_list = os.listdir(thermal_folder)
    print thermal_file_list
    print len(thermal_file_list)
    thermal_face_means = []
    for i, f in enumerate(thermal_file_list):
        thermal_file = os.path.join(thermal_folder, f)
#         print thermal_file
        thermal_vid = np.load(thermal_file)
        for i in range(thermal_vid.shape[2]):
            thermal_face_means.append(np.mean(thermal_vid[:,:,i]))
    
    print presentation
#     print thermal_face_means
    return thermal_face_means


'''
'''
def generate_fr_score_dists(ax, bonafide, attack, cls_thresh=0, perc_thresh=None, max_count=700, far_flag=False, legend_flag=True, batch_name='Batch'):
    """
    This function plots FR score-distributions. 
    Inputs:
    ax: axes of a pyplot figure, where the plots will be constructed.
    genuine: list of genuine-presentation scores (histogram plotted in green)
    zei: list of zero-effort-impostor scores (histogram plotted in red, if list is not empty)
    pa_fr: list of face-recognition scores for presentation-attacks (histogram plotted in black, if list is not empty)
    legend_flag: boolean. If True, the legend for the plot is displayed above the main plot.
    batch_name: string. Text-label on right-side of the plot, to identify which batch this plot corresponds to.
    """
    n_bins = 100
    
#     y_axis_top = max_count

    min_bf = min(bonafide)
    min_attack = min(attack)
    max_bf = max(bonafide)
    max_attack = max(attack)
    min_score = min(min_bf, min_attack)
    max_score = max(max_bf, max_attack)
    score_range = (min_score, max_score)
    histoargs = {'bins': n_bins, 'alpha': 0.8, 'histtype': 'step', 'range': score_range} 
    lineargs = {'alpha': 0.5}
#     axis_fontsize = 8

    
    ax.tick_params(axis='both', which='major', labelsize=10)
#     ax.set_ylim(bottom=0, top=y_axis_top)
    if bonafide:
        ax.hist(bonafide, label='Bonafide', color='g', **histoargs)
    if attack:
        hn, hbins, hpatches =  ax.hist(attack, label='Attacks', color='r', **histoargs)
        
    _, _, ymax, ymin = ax.axis()
    cls_thrStr = "{:2.5f}".format(cls_thresh)
    ax.vlines(cls_thresh, ymin, ymax, color='m', label='cls Thr.:'+cls_thrStr, linestyles='solid', **lineargs)
#     if legend_flag:
    ax.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=4, mode="expand", borderaxespad=0., fontsize=10)
    ax.grid(True, alpha=0.3)


    plt.show()


'''
'''
#     def generate_plots(dev_pos, dev_neg, test_pos, test_neg, args, plot_title=''):
#     """
def generate_plots(dev_pos, dev_neg, plot_title=''):
    """
    This function will plot score-distributions and DET curves ...
    returns a figure
    """

    # get threshold as min EER on development set, compute error rates
    eer_thresh = bob.measure.eer_threshold(dev_neg, dev_pos)
    print eer_thresh
    devel_far, devel_frr = bob.measure.farfrr(dev_neg, dev_pos, eer_thresh)
    devel_hter = 50 * (devel_far + devel_frr)
    #test_hter = devel_hter
     
#     test_far, test_frr = bob.measure.farfrr(test_neg, test_pos, thresh)
#     test_hter = 50 * (test_far + test_frr)
#     
    # figures
    fig = P.figure(figsize=(7, 5), dpi=100)
    P.suptitle(plot_title)
    lines = []

    # plot the distribution of the scores
    mybins = 100
    min_score_neg = np.amin(dev_neg) #min(np.amin(test_neg), np.amin(dev_neg))
    min_score_pos = np.amin(dev_pos) #min(np.amin(test_pos), np.amin(dev_pos))
    
    max_score_pos = np.amax(dev_pos) #max(np.amax(test_pos), np.amax(dev_pos))
    max_score_neg = np.amax(dev_neg) #max(np.amax(test_neg), np.amax(dev_neg))
    
    min_score = min(min_score_neg, min_score_pos)
    max_score = max(max_score_neg, max_score_pos)
    scoresRange = (min_score, max_score)
    

    color_scheme = {'genuine': '#7bd425', 'impostors': '#257bd4',
                        'spoofs': 'black', 'line': '#d4257b'}

    alpha_scheme = {'genuine': 0.9, 'impostors': 0.8, 'spoofs': 0.4}
    hatch_scheme = {'genuine': None, 'impostors': None, 'spoofs': None}
    fontProperties = {'family': 'sans-serif', 'weight': 'normal'}
    
    P.subplot(1,1,1)
    ax1=P.gca()
    
#     ax1.set_xticklabels(ax1.get_xticks(), fontProperties)
#     ax1.set_yticklabels(ax1.get_yticks(), fontProperties)
#     prob_ax.set_yticklabels(prob_ax.get_yticks(), fontProperties)

    from matplotlib.ticker import FormatStrFormatter
    majorFormatter = FormatStrFormatter('%d')
#     prob_ax.yaxis.set_major_formatter(majorFormatter)
    majorFormatter = FormatStrFormatter('%.1f')
    ax1.xaxis.set_major_formatter(majorFormatter)


    line = P.hist(dev_pos, bins=10, color=color_scheme['genuine'],
                    alpha=alpha_scheme['genuine'],
                    hatch=hatch_scheme['genuine'],
                    label="Genuines", normed=True)
    lines.append(line[-1][0])
    line = P.hist(dev_neg, bins=10, color=color_scheme['spoofs'],
                    alpha=alpha_scheme['spoofs'],
                    hatch=hatch_scheme['spoofs'],
                    label="Presentation Attacks", normed=True)
    lines.append(line[-1][0])


    lineargs = {'alpha': 0.5}
#     histoargs = {'bins': mybins, 'alpha': 0.5, 'histtype': 'step', 'range': scoresRange} 
   
    axis_fontsize = 10

    # for the development set
    
#     P.hist(dev_pos, label='Real Accesses', color='g', **histoargs)
#     P.hist(dev_neg, label='Attacks', color='r', **histoargs)
    _, _, ymax, ymin = P.axis()
    threshStr = "{:2.3f}".format(eer_thresh)
    P.vlines(eer_thresh, ymin, ymax, color='blue', label='EER Thr.:'+threshStr, linestyles='solid', **lineargs)
    P.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=4, mode="expand", borderaxespad=0.)
#     if xlabel:
    P.xlabel("Mean thermal intensity in face-region")
#     if y1label:
    P.ylabel("Normalized count")

#     P.grid(True, alpha=0.5)
#     P.ylabel("Test set")
#     axis = P.gca()
#     axis.yaxis.set_label_position('right')
  
#     # for the test set
#     P.subplot(2,1,2)
#     P.hist(test_pos, label='Real Accesses', color='g', **histoargs)
#     P.hist(test_neg, label='Attacks', color='r', **histoargs)
#     _, _, ymax, ymin = P.axis()
#     P.vlines(thresh, ymin, ymax, color='blue', label='EER', linestyles='solid', **lineargs)
#     P.grid(True, alpha=0.5)
#     P.ylabel("Test set")
#     axis = P.gca()
#     axis.yaxis.set_label_position('right')

#     # DET curve for both sets
#     P.subplot(2,1,2)
#     hterDevelStr = "{:3.2f}".format(devel_hter)
# #     hterTestStr = "{:3.2f}".format(test_hter)
#      
#     bob.measure.plot.det(dev_neg, dev_pos, 100, axisfontsize='x-small', ls='--', color='blue', label='EER = ' + hterDevelStr + '%')
# #     bob.measure.plot.det(test_neg, test_pos, 100, axisfontsize='x-small', color='red', label='Test HTER = ' + hterTestStr + '%')
#      
#     P.grid(True)
#     P.xlabel('FAR (%)')
#     P.ylabel('FRR (%)')
#     P.title('DET')
#     P.legend(loc='upper right')
#     bob.measure.plot.det_axis((0.5,99,0.5,99))
    
    P.show()
    
    return fig, devel_hter

def plot_det(neg, pos, threshold):
        # DET curve for both sets
    fig = P.figure(figsize=(7, 5), dpi=100)
    P.subplot(1,1,1)
    hterDevelStr = "{:3.2f}".format(threshold)
#     hterTestStr = "{:3.2f}".format(test_hter)
    axis_fontsize = 10
    fontProperties = {'family': 'sans-serif', 'weight': 'normal'}
    
    bob.measure.plot.det(neg, pos, 100, axisfontsize=10, ls='--', color='blue', label='EER = ' + hterDevelStr + '%')
#     bob.measure.plot.det(test_neg, test_pos, 100, axisfontsize='x-small', color='red', label='Test HTER = ' + hterTestStr + '%')
    
    P.grid(True)
    P.xlabel('FAR (%)')
    P.ylabel('FRR (%)')
    P.title('DET')
    P.legend(loc='upper right')
    bob.measure.plot.det_axis((0.5,99,0.5,99))
    
    P.show()
    return fig
    

'''
'''
def main(arguments):
    
    #extract seek-thermal data from batl files
#     extract_seekthermal_data('bonafide')
#     extract_seekthermal_data('attack')
#     assert 0, 'stop'

    #extract RGB data from SR300 files
#     extract_sr300_data('bonafide')
#     extract_sr300_data('attack')
#     assert 0, 'stop'

#     sr300_rgb_to_gray('bonafide')
#     sr300_rgb_to_gray('attack')
#     assert 0, 'stop'

#     extract_thermal_face('bonafide')
#     extract_thermal_face('attack')
#     assert 0, 'stop'    
    
    bonafide_thermal_face_means = get_thermal_face_mean('bonafide')
    
    print(len(bonafide_thermal_face_means))
    attack_thermal_face_means = get_thermal_face_mean('attack')
    print(len(attack_thermal_face_means))
    fig1, dev_eer = generate_plots(bonafide_thermal_face_means, attack_thermal_face_means, plot_title='')
    
    fig2 = plot_det(attack_thermal_face_means, bonafide_thermal_face_means, dev_eer)
    
    pad_res_file = bob.io.base.HDF5File('/idiap/temp/sbhatta/work/3DMask_Data/thermal_pad_scores.hdf5','w')
    pad_res_file.set('thermal_bonafide_scores', bonafide_thermal_face_means)
    pad_res_file.set('thermal_attack_scores', attack_thermal_face_means)
    del pad_res_file
    
    #'/idiap/home/sbhatta/disk_temp/work/3DMask_Data/SeekThermal/faces/bonafide_train'
#     presentation = 'bonafide_train'
#     train_thermal_face_means = get_thermal_face_mean(presentation)
#     training_thermal_mean = np.mean(np.asarray(train_thermal_face_means))
    # figures
#     fig_size = (9, 6.5)
#     ax = plt.gca()
#     generate_fr_score_dists(ax, bonafide_thermal_face_means, attack_thermal_face_means, cls_thresh= training_thermal_mean)
#     assert 0, 'stop!'


if __name__ == '__main__':
    main(sys.argv[1:])