view_sample.py 5.2 KB
Newer Older
André Anjos's avatar
André Anjos committed
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
#!/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:

  <database>  Path to the database with the image to be inspected
  <processed>  Path with the directory holding the preprocessed and extracted
               sub-directories containing the processing results of a
               bob.bio.vein toolchain
  <stem>       Name of the object on the database to display, with the root or
               the extension


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:

  Visualize to processing toolchain over a single image

     $ %(prog)s /database /mc client/sample

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

     $ %(prog)s /database /mc client/sample1 client/sample2

"""


import os
import sys

import numpy
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'))


96
def proof_figure(title, image, mask, image_pp, binary=None):
André Anjos's avatar
André Anjos committed
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
  '''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

114 115 116
    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
117 118 119 120 121 122 123 124 125


  Returns:

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

  '''

126 127 128
  fig = mpl.figure(figsize=(6,9), dpi=100)

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

  # add original image
131
  mpl.subplot(images, 1, 1)
André Anjos's avatar
André Anjos committed
132 133 134 135 136 137
  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)
138
  mpl.subplot(images, 1, 2)
André Anjos's avatar
André Anjos committed
139 140 141
  mpl.title('Preprocessed')
  mpl.imshow(img)

142 143 144 145 146
  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
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

  return fig


def main(user_input=None):

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

  import docopt
  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'],
      )

  # Sets-up logging
  verbosity = int(args['--verbose'])
  bob.core.log.set_verbosity_level(logger, verbosity)

  # Loads the image, the mask and save it to a PNG file
  for stem in args['<stem>']:
    image = bob.bio.base.load(os.path.join(args['<database>'], stem + '.png'))
179
    image = numpy.rot90(image, k=-1)
André Anjos's avatar
André Anjos committed
180 181 182 183
    pp = bob.io.base.HDF5File(os.path.join(args['<processed>'],
      'preprocessed', stem + '.hdf5'))
    mask  = pp.read('mask')
    image_pp = pp.read('image')
184 185 186 187 188
    binary_path = os.path.join(args['<processed>'], 'extracted', stem + '.hdf5')
    if os.path.exists(binary_path):
      binary = bob.io.base.load(binary_path)
    else:
      binary = None
André Anjos's avatar
André Anjos committed
189 190 191 192 193 194
    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...')