test.py 23.2 KB
Newer Older
Pedro TOME's avatar
Pedro TOME committed
1 2 3 4
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :


5 6 7 8 9 10 11 12
"""Unit tests against references extracted from

Matlab code from Bram Ton available on the matlab central website:

https://www.mathworks.com/matlabcentral/fileexchange/35754-wide-line-detector

This code implements the detector described in [HDLTL10] (see the references in
the generated sphinx documentation)
Pedro TOME's avatar
Pedro TOME committed
13 14 15
"""

import os
16 17 18
import numpy
import nose.tools

Pedro TOME's avatar
Pedro TOME committed
19 20
import pkg_resources

21 22
import bob.io.base
import bob.io.matlab
André Anjos's avatar
André Anjos committed
23
import bob.io.image
Pedro TOME's avatar
Pedro TOME committed
24

25
from ..preprocessor import utils as preprocessor_utils
26

Pedro TOME's avatar
Pedro TOME committed
27

28 29 30 31
def F(parts):
  """Returns the test file path"""

  return pkg_resources.resource_filename(__name__, os.path.join(*parts))
André Anjos's avatar
André Anjos committed
32

33

34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
def test_cropping():

  # tests if the cropping stage at preprocessors works as planned

  from ..preprocessor.crop import FixedCrop, NoCrop

  shape = (20, 17)
  test_image = numpy.random.randint(0, 1000, size=shape, dtype=int)

  dont_crop = NoCrop()
  cropped = dont_crop(test_image)
  nose.tools.eq_(test_image.shape, cropped.shape)
  nose.tools.eq_((test_image-cropped).sum(), 0)

  top = 5; bottom = 2; left=3; right=7
  fixed_crop = FixedCrop(top, bottom, left, right)
  cropped = fixed_crop(test_image)
  nose.tools.eq_(cropped.shape, (shape[0]-(top+bottom), shape[1]-(left+right)))
  nose.tools.eq_((test_image[top:-bottom,left:-right]-cropped).sum(), 0)

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
  # tests metadata survives after cropping (and it is corrected)
  from ..database import AnnotatedArray
  annotations = [
      (top-2, left+2), #slightly above and to the right
      (top+3, shape[1]-(right+1)+3), #slightly down and to the right
      (shape[0]-(bottom+1)+4, shape[1]-(right+1)-2),
      (shape[0]-(bottom+1)+1, left),
      ]
  annotated_image = AnnotatedArray(test_image, metadata=dict(roi=annotations))
  assert hasattr(annotated_image, 'metadata')
  cropped = fixed_crop(annotated_image)
  assert hasattr(cropped, 'metadata')
  assert numpy.allclose(cropped.metadata['roi'], [
    (0, 2),
    (3, cropped.shape[1]-1),
    (cropped.shape[0]-1, 4),
    (cropped.shape[0]-1, 0),
    ])

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

def test_masking():

  # tests if the masking stage at preprocessors work as planned

  from ..preprocessor.mask import FixedMask, NoMask, AnnotatedRoIMask
  from ..database import AnnotatedArray

  shape = (17, 20)
  test_image = numpy.random.randint(0, 1000, size=shape, dtype=int)

  masker = NoMask()
  mask = masker(test_image)
  nose.tools.eq_(mask.dtype, numpy.dtype('bool'))
  nose.tools.eq_(mask.shape, test_image.shape)
  nose.tools.eq_(mask.sum(), numpy.prod(shape))

  top = 4; bottom = 2; left=3; right=1
  masker = FixedMask(top, bottom, left, right)
  mask = masker(test_image)
  nose.tools.eq_(mask.dtype, numpy.dtype('bool'))
  nose.tools.eq_(mask.sum(), (shape[0]-(top+bottom)) * (shape[1]-(left+right)))
  nose.tools.eq_(mask[top:-bottom,left:-right].sum(), mask.sum())

  # this matches the previous "fixed" mask - notice we consider the pixels
  # under the polygon line to be **part** of the RoI (mask position == True)
  shape = (10, 10)
  test_image = numpy.random.randint(0, 1000, size=shape, dtype=int)
  annotations = [
      (top, left),
      (top, shape[1]-(right+1)),
      (shape[0]-(bottom+1), shape[1]-(right+1)),
      (shape[0]-(bottom+1), left),
      ]
  image = AnnotatedArray(test_image, metadata=dict(roi=annotations))
  masker = AnnotatedRoIMask()
  mask = masker(image)
  nose.tools.eq_(mask.dtype, numpy.dtype('bool'))
  nose.tools.eq_(mask.sum(), (shape[0]-(top+bottom)) * (shape[1]-(left+right)))
  nose.tools.eq_(mask[top:-bottom,left:-right].sum(), mask.sum())


def test_preprocessor():

  # tests the whole preprocessing mechanism, compares to matlab source
118

André Anjos's avatar
André Anjos committed
119 120
  input_filename = F(('preprocessors', '0019_3_1_120509-160517.png'))
  output_img_filename  = F(('preprocessors',
121
    '0019_3_1_120509-160517_img_lee_huang.mat'))
André Anjos's avatar
André Anjos committed
122
  output_fvr_filename  = F(('preprocessors',
123 124 125 126
    '0019_3_1_120509-160517_fvr_lee_huang.mat'))

  img = bob.io.base.load(input_filename)

127
  from ..preprocessor import Preprocessor, NoCrop, LeeMask, \
128 129 130
      HuangNormalization, NoFilter

  processor = Preprocessor(
131
      NoCrop(),
132 133 134 135 136
      LeeMask(filter_height=40, filter_width=4),
      HuangNormalization(padding_width=0, padding_constant=0),
      NoFilter(),
      )
  preproc, mask = processor(img)
137
  #preprocessor_utils.show_mask_over_image(preproc, mask)
138

139 140 141 142 143
  mask_ref = bob.io.base.load(output_fvr_filename).astype('bool')
  preproc_ref = bob.core.convert(bob.io.base.load(output_img_filename),
      numpy.uint8, (0,255), (0.0,1.0))

  assert numpy.mean(numpy.abs(mask - mask_ref)) < 1e-2
144

145
  # Very loose comparison!
146
  #preprocessor_utils.show_image(numpy.abs(preproc.astype('int16') - preproc_ref.astype('int16')).astype('uint8'))
147
  assert numpy.mean(numpy.abs(preproc - preproc_ref)) < 1.3e2
148 149


150
def test_max_curvature():
151 152 153

  #Maximum Curvature method against Matlab reference

154 155 156 157 158 159 160 161 162 163 164 165
  image = bob.io.base.load(F(('extractors', 'image.hdf5')))
  image = image.T
  image = image.astype('float64')/255.
  mask  = bob.io.base.load(F(('extractors', 'mask.hdf5')))
  mask  = mask.T
  mask  = mask.astype('bool')
  vt_ref = bob.io.base.load(F(('extractors', 'mc_vt_matlab.hdf5')))
  vt_ref = vt_ref.T
  g_ref = bob.io.base.load(F(('extractors', 'mc_g_matlab.hdf5')))
  g_ref = g_ref.T
  bin_ref = bob.io.base.load(F(('extractors', 'mc_bin_matlab.hdf5')))
  bin_ref = bin_ref.T
166 167

  # Apply Python implementation
168
  from ..extractor.MaximumCurvature import MaximumCurvature
169 170 171
  MC = MaximumCurvature(3) #value used to create references

  kappa = MC.detect_valleys(image, mask)
172
  Vt = MC.eval_vein_probabilities(kappa)
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
  Cd = MC.connect_centres(Vt)
  G = numpy.amax(Cd, axis=2)
  bina = MC.binarise(G)

  assert numpy.allclose(Vt, vt_ref, 1e-3, 1e-4), \
      'Vt differs from reference by %s' % numpy.abs(Vt-vt_ref).sum()
  # Note: due to Matlab implementation bug, can only compare in a limited
  # range with a 3-pixel around frame
  assert numpy.allclose(G[2:-3,2:-3], g_ref[2:-3,2:-3]), \
      'G differs from reference by %s' % numpy.abs(G-g_ref).sum()
  # We require no more than 30 pixels (from a total of 63'840) are different
  # between ours and the matlab implementation
  assert numpy.abs(bin_ref-bina).sum() < 30, \
      'Binarized image differs from reference by %s' % \
      numpy.abs(bin_ref-bina).sum()
Pedro TOME's avatar
Pedro TOME committed
188 189


Vedrana KRIVOKUCA's avatar
Vedrana KRIVOKUCA committed
190 191 192 193 194 195
def test_max_curvature_HE():
  # Maximum Curvature method when Histogram Equalization post-processing is applied to the preprocessed vein image

  # Read in input image
  input_img_filename = F(('preprocessors', '0019_3_1_120509-160517.png'))
  input_img = bob.io.base.load(input_img_filename)
André Anjos's avatar
André Anjos committed
196

Vedrana KRIVOKUCA's avatar
Vedrana KRIVOKUCA committed
197
  # Preprocess the data and apply Histogram Equalization postprocessing (same parameters as in maximum_curvature.py configuration file + postprocessing)
198
  from ..preprocessor import Preprocessor, NoCrop, LeeMask, \
199 200
      HuangNormalization, HistogramEqualization
  processor = Preprocessor(
201
      NoCrop(),
202 203 204 205 206
      LeeMask(filter_height=40, filter_width=4),
      HuangNormalization(padding_width=0, padding_constant=0),
      HistogramEqualization(),
      )
  preproc_data = processor(input_img)
Vedrana KRIVOKUCA's avatar
Vedrana KRIVOKUCA committed
207 208

  # Extract features from preprocessed and histogram equalized data using MC extractor (same parameters as in maximum_curvature.py configuration file)
209
  from ..extractor.MaximumCurvature import MaximumCurvature
Vedrana KRIVOKUCA's avatar
Vedrana KRIVOKUCA committed
210 211
  MC = MaximumCurvature(sigma = 5)
  extr_data = MC(preproc_data)
212
  #preprocessor_utils.show_image((255.*extr_data).astype('uint8'))
Vedrana KRIVOKUCA's avatar
Vedrana KRIVOKUCA committed
213 214


215
def test_repeated_line_tracking():
216 217 218

  #Repeated Line Tracking method against Matlab reference

André Anjos's avatar
André Anjos committed
219 220 221
  input_img_filename  = F(('extractors', 'miurarlt_input_img.mat'))
  input_fvr_filename  = F(('extractors', 'miurarlt_input_fvr.mat'))
  output_filename     = F(('extractors', 'miurarlt_output.mat'))
222 223 224 225 226 227

  # Load inputs
  input_img = bob.io.base.load(input_img_filename)
  input_fvr = bob.io.base.load(input_fvr_filename)

  # Apply Python implementation
228
  from ..extractor.RepeatedLineTracking import RepeatedLineTracking
229 230 231 232 233 234 235 236 237 238 239
  RLT = RepeatedLineTracking(3000, 1, 21, False)
  output_img = RLT((input_img, input_fvr))

  # Load Matlab reference
  output_img_ref = bob.io.base.load(output_filename)

  # Compare output of python's implementation to matlab reference
  # (loose comparison!)
  assert numpy.mean(numpy.abs(output_img - output_img_ref)) < 0.5


Vedrana KRIVOKUCA's avatar
Vedrana KRIVOKUCA committed
240 241 242 243 244 245
def test_repeated_line_tracking_HE():
  # Repeated Line Tracking method when Histogram Equalization post-processing is applied to the preprocessed vein image

  # Read in input image
  input_img_filename = F(('preprocessors', '0019_3_1_120509-160517.png'))
  input_img = bob.io.base.load(input_img_filename)
André Anjos's avatar
André Anjos committed
246

Vedrana KRIVOKUCA's avatar
Vedrana KRIVOKUCA committed
247
  # Preprocess the data and apply Histogram Equalization postprocessing (same parameters as in repeated_line_tracking.py configuration file + postprocessing)
248
  from ..preprocessor import Preprocessor, NoCrop, LeeMask, \
249 250
      HuangNormalization, HistogramEqualization
  processor = Preprocessor(
251
      NoCrop(),
252 253 254 255 256
      LeeMask(filter_height=40, filter_width=4),
      HuangNormalization(padding_width=0, padding_constant=0),
      HistogramEqualization(),
      )
  preproc_data = processor(input_img)
Vedrana KRIVOKUCA's avatar
Vedrana KRIVOKUCA committed
257 258

  # Extract features from preprocessed and histogram equalized data using RLT extractor (same parameters as in repeated_line_tracking.py configuration file)
259
  from ..extractor.RepeatedLineTracking import RepeatedLineTracking
Vedrana KRIVOKUCA's avatar
Vedrana KRIVOKUCA committed
260 261 262 263 264 265 266 267 268 269
  # Maximum number of iterations
  NUMBER_ITERATIONS = 3000
  # Distance between tracking point and cross section of profile
  DISTANCE_R = 1
  # Width of profile
  PROFILE_WIDTH = 21
  RLT = RepeatedLineTracking(iterations = NUMBER_ITERATIONS, r = DISTANCE_R, profile_w = PROFILE_WIDTH, seed = 0)
  extr_data = RLT(preproc_data)


270
def test_wide_line_detector():
271 272 273

  #Wide Line Detector method against Matlab reference

André Anjos's avatar
André Anjos committed
274 275 276
  input_img_filename  = F(('extractors', 'huangwl_input_img.mat'))
  input_fvr_filename  = F(('extractors', 'huangwl_input_fvr.mat'))
  output_filename     = F(('extractors', 'huangwl_output.mat'))
277 278 279 280 281 282

  # Load inputs
  input_img = bob.io.base.load(input_img_filename)
  input_fvr = bob.io.base.load(input_fvr_filename)

  # Apply Python implementation
283
  from ..extractor.WideLineDetector import WideLineDetector
284 285 286 287 288 289 290 291 292 293
  WL = WideLineDetector(5, 1, 41, False)
  output_img = WL((input_img, input_fvr))

  # Load Matlab reference
  output_img_ref = bob.io.base.load(output_filename)

  # Compare output of python's implementation to matlab reference
  assert numpy.allclose(output_img, output_img_ref)


Vedrana KRIVOKUCA's avatar
Vedrana KRIVOKUCA committed
294 295 296 297 298 299
def test_wide_line_detector_HE():
  # Wide Line Detector method when Histogram Equalization post-processing is applied to the preprocessed vein image

  # Read in input image
  input_img_filename = F(('preprocessors', '0019_3_1_120509-160517.png'))
  input_img = bob.io.base.load(input_img_filename)
André Anjos's avatar
André Anjos committed
300

Vedrana KRIVOKUCA's avatar
Vedrana KRIVOKUCA committed
301
  # Preprocess the data and apply Histogram Equalization postprocessing (same parameters as in wide_line_detector.py configuration file + postprocessing)
302
  from ..preprocessor import Preprocessor, NoCrop, LeeMask, \
303 304
      HuangNormalization, HistogramEqualization
  processor = Preprocessor(
305
      NoCrop(),
306 307 308 309 310
      LeeMask(filter_height=40, filter_width=4),
      HuangNormalization(padding_width=0, padding_constant=0),
      HistogramEqualization(),
      )
  preproc_data = processor(input_img)
Vedrana KRIVOKUCA's avatar
Vedrana KRIVOKUCA committed
311 312

  # Extract features from preprocessed and histogram equalized data using WLD extractor (same parameters as in wide_line_detector.py configuration file)
313
  from ..extractor.WideLineDetector import WideLineDetector
Vedrana KRIVOKUCA's avatar
Vedrana KRIVOKUCA committed
314 315 316 317 318 319 320 321 322 323
  # Radius of the circular neighbourhood region
  RADIUS_NEIGHBOURHOOD_REGION = 5
  NEIGHBOURHOOD_THRESHOLD = 1
  # Sum of neigbourhood threshold
  SUM_NEIGHBOURHOOD = 41
  RESCALE = True
  WLD = WideLineDetector(radius = RADIUS_NEIGHBOURHOOD_REGION, threshold = NEIGHBOURHOOD_THRESHOLD, g = SUM_NEIGHBOURHOOD, rescale = RESCALE)
  extr_data = WLD(preproc_data)


324 325
def test_miura_match():

André Anjos's avatar
André Anjos committed
326 327 328 329 330
  #Match Ratio method against Matlab reference

  template_filename = F(('algorithms', '0001_2_1_120509-135338.mat'))
  probe_gen_filename = F(('algorithms', '0001_2_2_120509-135558.mat'))
  probe_imp_filename = F(('algorithms', '0003_2_1_120509-141255.mat'))
331 332 333 334 335

  template_vein = bob.io.base.load(template_filename)
  probe_gen_vein = bob.io.base.load(probe_gen_filename)
  probe_imp_vein = bob.io.base.load(probe_imp_filename)

336
  from ..algorithm.MiuraMatch import MiuraMatch
337 338 339 340 341 342 343
  MM = MiuraMatch(ch=18, cw=28)
  score_gen = MM.score(template_vein, probe_gen_vein)

  assert numpy.isclose(score_gen, 0.382689335394127)

  score_imp = MM.score(template_vein, probe_imp_vein)
  assert numpy.isclose(score_imp, 0.172906739278421)
344 345 346 347 348 349 350


def test_assert_points():

  # Tests that point assertion works as expected
  area = (10, 5)
  inside = [(0,0), (3,2), (9, 4)]
351
  preprocessor_utils.assert_points(area, inside) #should not raise
352 353 354 355

  def _check_outside(point):
    # should raise, otherwise it is an error
    try:
356
      preprocessor_utils.assert_points(area, [point])
357 358 359 360 361 362 363 364 365 366 367 368 369 370
    except AssertionError as e:
      assert str(point) in str(e)
    else:
      raise AssertionError("Did not assert %s is outside of %s" % (point, area))

  outside = [(-1, 0), (10, 0), (0, 5), (10, 5), (15,12)]
  for k in outside: _check_outside(k)


def test_fix_points():

  # Tests that point clipping works as expected
  area = (10, 5)
  inside = [(0,0), (3,2), (9, 4)]
371
  fixed = preprocessor_utils.fix_points(area, inside)
372 373
  assert numpy.array_equal(inside, fixed), '%r != %r' % (inside, fixed)

374
  fixed = preprocessor_utils.fix_points(area, [(-1, 0)])
375 376
  assert numpy.array_equal(fixed, [(0, 0)])

377
  fixed = preprocessor_utils.fix_points(area, [(10, 0)])
378 379
  assert numpy.array_equal(fixed, [(9, 0)])

380
  fixed = preprocessor_utils.fix_points(area, [(0, 5)])
381 382
  assert numpy.array_equal(fixed, [(0, 4)])

383
  fixed = preprocessor_utils.fix_points(area, [(10, 5)])
384 385
  assert numpy.array_equal(fixed, [(9, 4)])

386
  fixed = preprocessor_utils.fix_points(area, [(15, 12)])
387 388 389 390 391 392 393 394
  assert numpy.array_equal(fixed, [(9, 4)])


def test_poly_to_mask():

  # Tests we can generate a mask out of a polygon correctly
  area = (10, 9) #10 rows, 9 columns
  polygon = [(2, 2), (2, 7), (7, 7), (7, 2)] #square shape, (y, x) format
395
  mask = preprocessor_utils.poly_to_mask(area, polygon)
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
  nose.tools.eq_(mask.dtype, numpy.bool)

  # This should be the output:
  expected = numpy.array([
      [False, False, False, False, False, False, False, False, False],
      [False, False, False, False, False, False, False, False, False],
      [False, False, True,  True,  True,  True,  True,  True,  False],
      [False, False, True,  True,  True,  True,  True,  True,  False],
      [False, False, True,  True,  True,  True,  True,  True,  False],
      [False, False, True,  True,  True,  True,  True,  True,  False],
      [False, False, True,  True,  True,  True,  True,  True,  False],
      [False, False, True,  True,  True,  True,  True,  True,  False],
      [False, False, False, False, False, False, False, False, False],
      [False, False, False, False, False, False, False, False, False],
      ])
  assert numpy.array_equal(mask, expected)

  polygon = [(3, 2), (5, 7), (8, 7), (7, 3)] #trapezoid, (y, x) format
414
  mask = preprocessor_utils.poly_to_mask(area, polygon)
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
  nose.tools.eq_(mask.dtype, numpy.bool)

  # This should be the output:
  expected = numpy.array([
      [False, False, False, False, False, False, False, False, False],
      [False, False, False, False, False, False, False, False, False],
      [False, False, False, False, False, False, False, False, False],
      [False, False, True,  False, False, False, False, False, False],
      [False, False, True,  True,  True,  False, False, False, False],
      [False, False, False, True,  True,  True,  True,  True,  False],
      [False, False, False, True,  True,  True,  True,  True,  False],
      [False, False, False, True,  True,  True,  True,  True,  False],
      [False, False, False, False, False, False, False, True,  False],
      [False, False, False, False, False, False, False, False, False],
      ])
  assert numpy.array_equal(mask, expected)


def test_mask_to_image():

  # Tests we can correctly convert a boolean array into an image
  # that makes sense according to the data types
  sample = numpy.array([False, True])
  nose.tools.eq_(sample.dtype, numpy.bool)

  def _check_uint(n):
441
    conv = preprocessor_utils.mask_to_image(sample, 'uint%d' % n)
442 443 444 445 446 447 448 449 450 451
    nose.tools.eq_(conv.dtype, getattr(numpy, 'uint%d' % n))
    target = [0, (2**n)-1]
    assert numpy.array_equal(conv, target), '%r != %r' % (conv, target)

  _check_uint(8)
  _check_uint(16)
  _check_uint(32)
  _check_uint(64)

  def _check_float(n):
452
    conv = preprocessor_utils.mask_to_image(sample, 'float%d' % n)
453 454 455 456 457 458 459 460 461 462
    nose.tools.eq_(conv.dtype, getattr(numpy, 'float%d' % n))
    assert numpy.array_equal(conv, [0, 1.0]), '%r != %r' % (conv, target)

  _check_float(32)
  _check_float(64)
  _check_float(128)


  # This should be unsupported
  try:
463
    conv = preprocessor_utils.mask_to_image(sample, 'int16')
464 465 466 467
  except TypeError as e:
    assert 'int16' in str(e)
  else:
    raise AssertionError('Conversion to int16 did not trigger a TypeError')
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482


def test_jaccard_index():

  # Tests to verify the Jaccard index calculation is accurate
  a = numpy.array([
    [False, False],
    [True, True],
    ])

  b = numpy.array([
    [True, True],
    [True, False],
    ])

483 484 485 486 487 488 489
  nose.tools.eq_(preprocessor_utils.jaccard_index(a, b), 1.0/4.0)
  nose.tools.eq_(preprocessor_utils.jaccard_index(a, a), 1.0)
  nose.tools.eq_(preprocessor_utils.jaccard_index(b, b), 1.0)
  nose.tools.eq_(preprocessor_utils.jaccard_index(a, numpy.ones(a.shape, dtype=bool)), 2.0/4.0)
  nose.tools.eq_(preprocessor_utils.jaccard_index(a, numpy.zeros(a.shape, dtype=bool)), 0.0)
  nose.tools.eq_(preprocessor_utils.jaccard_index(b, numpy.ones(b.shape, dtype=bool)), 3.0/4.0)
  nose.tools.eq_(preprocessor_utils.jaccard_index(b, numpy.zeros(b.shape, dtype=bool)), 0.0)
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504


def test_intersection_ratio():

  # Tests to verify the intersection ratio calculation is accurate
  a = numpy.array([
    [False, False],
    [True, True],
    ])

  b = numpy.array([
    [True, False],
    [True, False],
    ])

505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
  nose.tools.eq_(preprocessor_utils.intersect_ratio(a, b), 1.0/2.0)
  nose.tools.eq_(preprocessor_utils.intersect_ratio(a, a), 1.0)
  nose.tools.eq_(preprocessor_utils.intersect_ratio(b, b), 1.0)
  nose.tools.eq_(preprocessor_utils.intersect_ratio(a, numpy.ones(a.shape, dtype=bool)), 1.0)
  nose.tools.eq_(preprocessor_utils.intersect_ratio(a, numpy.zeros(a.shape, dtype=bool)), 0)
  nose.tools.eq_(preprocessor_utils.intersect_ratio(b, numpy.ones(b.shape, dtype=bool)), 1.0)
  nose.tools.eq_(preprocessor_utils.intersect_ratio(b, numpy.zeros(b.shape, dtype=bool)), 0)

  nose.tools.eq_(preprocessor_utils.intersect_ratio_of_complement(a, b), 1.0/2.0)
  nose.tools.eq_(preprocessor_utils.intersect_ratio_of_complement(a, a), 0.0)
  nose.tools.eq_(preprocessor_utils.intersect_ratio_of_complement(b, b), 0.0)
  nose.tools.eq_(preprocessor_utils.intersect_ratio_of_complement(a, numpy.ones(a.shape, dtype=bool)), 1.0)
  nose.tools.eq_(preprocessor_utils.intersect_ratio_of_complement(a, numpy.zeros(a.shape, dtype=bool)), 0)
  nose.tools.eq_(preprocessor_utils.intersect_ratio_of_complement(b, numpy.ones(b.shape, dtype=bool)), 1.0)
  nose.tools.eq_(preprocessor_utils.intersect_ratio_of_complement(b, numpy.zeros(b.shape, dtype=bool)), 0)


522
def test_correlation():
523

524
  # A test for convolution performance. Correlations are used on the Miura
525 526
  # Match algorithm, therefore we want to make sure we can perform them as fast
  # as possible.
527
  import numpy
528
  import scipy.signal
529
  import bob.sp
530

531
  # Rough example from Vera fingervein database
532 533
  Y = 250
  X = 600
534 535
  CH = 80
  CW = 90
536 537 538 539 540 541

  def gen_ab():
    a = numpy.random.randint(256, size=(Y, X)).astype(float)
    b = numpy.random.randint(256, size=(Y-CH, X-CW)).astype(float)
    return a, b

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

  def bob_function(a, b):

    # rotate input image by 180 degrees
    b = numpy.rot90(b, k=2)

    # Determine padding size in x and y dimension
    size_a  = numpy.array(a.shape)
    size_b  = numpy.array(b.shape)
    outsize = size_a + size_b - 1

    # Determine 2D cross correlation in Fourier domain
    a2 = numpy.zeros(outsize)
    a2[0:size_a[0],0:size_a[1]] = a
    Fa = bob.sp.fft(a2.astype(numpy.complex128))

    b2 = numpy.zeros(outsize)
    b2[0:size_b[0],0:size_b[1]] = b
    Fb = bob.sp.fft(b2.astype(numpy.complex128))

    conv_ab = numpy.real(bob.sp.ifft(Fa*Fb))

    h, w = size_a - size_b + 1

    Nm = conv_ab[size_b[0]-1:size_b[0]-1+h, size_b[1]-1:size_b[1]-1+w]

    t0, s0 = numpy.unravel_index(Nm.argmax(), Nm.shape)

    # this is our output
    Nmm = Nm[t0,s0]

    # normalizes the output by the number of pixels lit on the input
    # matrices, taking into consideration the surface that produced the
    # result (i.e., the eroded model and part of the probe)
    h, w = b.shape
    return Nmm/(sum(sum(b)) + sum(sum(a[t0:t0+h-2*CH, s0:s0+w-2*CW])))

579 580

  def scipy_function(a, b):
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
    b = numpy.rot90(b, k=2)

    Nm = scipy.signal.convolve2d(a, b, 'valid')

    # figures out where the maximum is on the resulting matrix
    t0, s0 = numpy.unravel_index(Nm.argmax(), Nm.shape)

    # this is our output
    Nmm = Nm[t0,s0]

    # normalizes the output by the number of pixels lit on the input
    # matrices, taking into consideration the surface that produced the
    # result (i.e., the eroded model and part of the probe)
    h, w = b.shape
    return Nmm/(sum(sum(b)) + sum(sum(a[t0:t0+h-2*CH, s0:s0+w-2*CW])))

597 598

  def scipy2_function(a, b):
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
    b = numpy.rot90(b, k=2)
    Nm = scipy.signal.fftconvolve(a, b, 'valid')

    # figures out where the maximum is on the resulting matrix
    t0, s0 = numpy.unravel_index(Nm.argmax(), Nm.shape)

    # this is our output
    Nmm = Nm[t0,s0]

    # normalizes the output by the number of pixels lit on the input
    # matrices, taking into consideration the surface that produced the
    # result (i.e., the eroded model and part of the probe)
    h, w = b.shape
    return Nmm/(sum(sum(b)) + sum(sum(a[t0:t0+h-2*CH, s0:s0+w-2*CW])))


  def scipy3_function(a, b):
    Nm = scipy.signal.correlate2d(a, b, 'valid')

    # figures out where the maximum is on the resulting matrix
    t0, s0 = numpy.unravel_index(Nm.argmax(), Nm.shape)

    # this is our output
    Nmm = Nm[t0,s0]

    # normalizes the output by the number of pixels lit on the input
    # matrices, taking into consideration the surface that produced the
    # result (i.e., the eroded model and part of the probe)
    h, w = b.shape
    return Nmm/(sum(sum(b)) + sum(sum(a[t0:t0+h-2*CH, s0:s0+w-2*CW])))
629 630

  a, b = gen_ab()
631 632

  assert numpy.allclose(bob_function(a, b), scipy_function(a, b))
633
  assert numpy.allclose(scipy_function(a, b), scipy2_function(a, b))
634
  assert numpy.allclose(scipy2_function(a, b), scipy3_function(a, b))
635

636 637
  # if you want to test timings, uncomment the following section
  '''
638 639 640 641 642 643
  import time

  start = time.clock()
  N = 10
  for i in range(N):
    a, b = gen_ab()
644
    bob_function(a, b)
645
  total = time.clock() - start
646
  print('bob implementation, %d iterations - %.2e per iteration' % (N, total/N))
647 648 649 650 651 652

  start = time.clock()
  for i in range(N):
    a, b = gen_ab()
    scipy_function(a, b)
  total = time.clock() - start
653
  print('scipy+convolve, %d iterations - %.2e per iteration' % (N, total/N))
654 655 656 657 658 659

  start = time.clock()
  for i in range(N):
    a, b = gen_ab()
    scipy2_function(a, b)
  total = time.clock() - start
660 661 662 663 664 665 666 667 668
  print('scipy+fftconvolve, %d iterations - %.2e per iteration' % (N, total/N))

  start = time.clock()
  for i in range(N):
    a, b = gen_ab()
    scipy3_function(a, b)
  total = time.clock() - start
  print('scipy+correlate2d, %d iterations - %.2e per iteration' % (N, total/N))
  '''