view_sample.py 6.78 KB
Newer Older
André Anjos's avatar
André Anjos committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Mon 07 Nov 2016 15:20:26 CET


"""Visualizes a particular sample throughout many processing stages

Usage: %(prog)s [-v...] [-s <path>] <database> <processed> <stem> [<stem>...]
       %(prog)s --help
       %(prog)s --version


Arguments:

15 16
  <database>   Name of the database to use for creating the model (options are:
               "fv3d" or "verafinger")
André Anjos's avatar
André Anjos committed
17 18 19
  <processed>  Path with the directory holding the preprocessed and extracted
               sub-directories containing the processing results of a
               bob.bio.vein toolchain
20 21
  <stem>       Name of the object on the database to display, without the root
               or the extension
André Anjos's avatar
André Anjos committed
22 23 24 25 26 27 28 29 30 31 32 33 34


Options:

  -h, --help                Shows this help message and exits
  -V, --version             Prints the version and exits
  -v, --verbose             Increases the output verbosity level
  -s <path>, --save=<path>  If set, saves image into a file instead of
                            displaying it


Examples:

35
  Visualize to processing toolchain over a single image of VERA finger vein:
André Anjos's avatar
André Anjos committed
36

37
     $ %(prog)s verafinger /mc client/sample
André Anjos's avatar
André Anjos committed
38 39 40

  Visualize multiple masks (like in a proof-sheet):

41
     $ %(prog)s verafinger /mc client/sample1 client/sample2
André Anjos's avatar
André Anjos committed
42 43 44 45 46 47 48 49

"""


import os
import sys

import numpy
50 51 52 53

import schema
import docopt

André Anjos's avatar
André Anjos committed
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
import bob.core
logger = bob.core.log.setup("bob.bio.vein")

import matplotlib.pyplot as mpl
from ..preprocessor import utils

import bob.io.base
import bob.io.image


def save_figures(title, image, mask, image_pp, binary):
  '''Saves individual images on a directory


  Parameters:

    title (str): A title for this plot

    image (numpy.ndarray): The original image representing the finger vein (2D
      array with dtype = ``uint8``)

    mask (numpy.ndarray): A 2D boolean array with the same size of the original
      image containing the pixels in which the image is valid (``True``) or
      invalid (``False``).

    image_pp (numpy.ndarray): A version of the original image, pre-processed by
      one of the available algorithms

    binary (numpy.ndarray): A binarized version of the original image in which
      all pixels (should) represent vein (``True``) or not-vein (``False``)

  '''

  os.makedirs(title)
  bob.io.base.save(image, os.path.join(title, 'original.png'))

  # add preprocessed image
  from ..preprocessor import utils
  img = utils.draw_mask_over_image(image_pp, mask)
  img = numpy.array(img).transpose(2,0,1)
  bob.io.base.save(img[:3], os.path.join(title, 'preprocessed.png'))

  # add binary image
  bob.io.base.save(binary.astype('uint8')*255, os.path.join(title,
    'binarized.png'))


101
def proof_figure(title, image, mask, image_pp, binary=None):
André Anjos's avatar
André Anjos committed
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
  '''Builds a proof canvas out of individual images


  Parameters:

    title (str): A title for this plot

    image (numpy.ndarray): The original image representing the finger vein (2D
      array with dtype = ``uint8``)

    mask (numpy.ndarray): A 2D boolean array with the same size of the original
      image containing the pixels in which the image is valid (``True``) or
      invalid (``False``).

    image_pp (numpy.ndarray): A version of the original image, pre-processed by
      one of the available algorithms

119 120 121
    binary (numpy.ndarray, Optional): A binarized version of the original image
      in which all pixels (should) represent vein (``True``) or not-vein
      (``False``)
André Anjos's avatar
André Anjos committed
122 123 124 125 126 127 128 129 130


  Returns:

    matplotlib.pyplot.Figure: A figure canvas containing the proof for the
    particular sample on the database

  '''

131 132 133
  fig = mpl.figure(figsize=(6,9), dpi=100)

  images = 3 if binary is not None else 2
André Anjos's avatar
André Anjos committed
134 135

  # add original image
136
  mpl.subplot(images, 1, 1)
André Anjos's avatar
André Anjos committed
137 138 139 140 141 142
  mpl.title('%s - original' % title)
  mpl.imshow(image, cmap="gray")

  # add preprocessed image
  from ..preprocessor import utils
  img = utils.draw_mask_over_image(image_pp, mask)
143
  mpl.subplot(images, 1, 2)
André Anjos's avatar
André Anjos committed
144 145 146
  mpl.title('Preprocessed')
  mpl.imshow(img)

147 148 149 150 151
  if binary is not None:
    # add binary image
    mpl.subplot(3, 1, 3)
    mpl.title('Binarized')
    mpl.imshow(binary.astype('uint8')*255, cmap="gray")
André Anjos's avatar
André Anjos committed
152 153 154 155

  return fig


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
def validate(args):
  '''Validates command-line arguments, returns parsed values

  This function uses :py:mod:`schema` for validating :py:mod:`docopt`
  arguments. Logging level is not checked by this procedure (actually, it is
  ignored) and must be previously setup as some of the elements here may use
  logging for outputing information.


  Parameters:

    args (dict): Dictionary of arguments as defined by the help message and
      returned by :py:mod:`docopt`


  Returns

    dict: Validate dictionary with the same keys as the input and with values
      possibly transformed by the validation procedure


  Raises:

    schema.SchemaError: in case one of the checked options does not validate.

  '''

  sch = schema.Schema({
    '<database>': lambda n: n in ('fv3d', 'verafinger'),
    str: object, #ignores strings we don't care about
    }, ignore_extra_keys=True)

  return sch.validate(args)


André Anjos's avatar
André Anjos committed
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
def main(user_input=None):

  if user_input is not None:
    argv = user_input
  else:
    argv = sys.argv[1:]

  import pkg_resources

  completions = dict(
      prog=os.path.basename(sys.argv[0]),
      version=pkg_resources.require('bob.bio.vein')[0].version
      )

  args = docopt.docopt(
      __doc__ % completions,
      argv=argv,
      version=completions['version'],
      )

211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
  try:
    from .validate import setup_logger
    logger = setup_logger('bob.bio.vein', args['--verbose'])
    args = validate(args)
  except schema.SchemaError as e:
    sys.exit(e)

  if args['<database>'] == 'fv3d':
    from ..configurations.fv3d import database as db
  elif args['<database>'] == 'verafinger':
    from ..configurations.verafinger import database as db
  else:
    raise schema.SchemaError('Database %s is not supported' % \
        args['<database>'])

  database_replacement = "%s/.bob_bio_databases.txt" % os.environ["HOME"]
  db.replace_directories(database_replacement)
  all_files = db.objects()
André Anjos's avatar
André Anjos committed
229 230 231

  # Loads the image, the mask and save it to a PNG file
  for stem in args['<stem>']:
232 233 234 235 236 237 238 239 240
    f = [k for k in all_files if k.path == stem]
    if len(f) == 0:
      raise RuntimeError('File with stem "%s" does not exist on "%s"' % \
          stem, args['<database>'])
    f = f[0]
    image = f.load(db.original_directory, db.original_extension)
    pp_name = f.make_path(os.path.join(args['<processed>'], 'preprocessed'),
        extension='.hdf5')
    pp = bob.io.base.HDF5File(pp_name)
André Anjos's avatar
André Anjos committed
241 242
    mask  = pp.read('mask')
    image_pp = pp.read('image')
243 244 245
    try:
      binary = f.load(os.path.join(args['<processed>'], 'extracted'))
    except:
246
      binary = None
André Anjos's avatar
André Anjos committed
247 248 249 250 251 252
    fig = proof_figure(stem, image, mask, image_pp, binary)
    if args['--save']:
      save_figures(args['--save'], image, mask, image_pp, binary)
    else:
      mpl.show()
      print('Close window to continue...')