Commit c4c828a6 authored by Guillaume HEUSCH's avatar Guillaume HEUSCH
Browse files

populating the directory with initial files

parent 09dc6843
This diff is collapsed.
include README.rst bootstrap-buildout.py buildout.cfg COPYING version.txt requirements.txt
recursive-include doc *.py *.rst
# see https://docs.python.org/3/library/pkgutil.html
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
# see https://docs.python.org/3/library/pkgutil.html
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from . import script
def get_config():
"""Returns a string containing the configuration information.
"""
import bob.extension
return bob.extension.get_config(__name__)
# gets sphinx autodoc done right - don't remove it
__all__ = [_ for _ in dir() if not _.startswith('_')]
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Andre Anjos <andre.dos.anjos@gmail.com>
# Wed 15 Aug 09:59:33 2012
#
# Copyright (C) 2011-2013 Idiap Research Institute, Martigny, Switzerland
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Test Units
"""
def test_version():
from .script import version
assert version.main() == 0
#!/usr/bin/env python
# encoding: utf-8
# Guillaume HEUSCH <guillaume.heusch@idiap.ch>
# Wed 29 Jul 09:27:26 CEST 2015
import sys
import numpy
class SkinColorFilter():
"""
This class implements a number of functions to perform skin color filtering. It is based on the work published in
"Adaptive skin segmentation via feature-based face detection", M.J. Taylor and T. Morris, Proc SPIE Photonics Europe, 2014
"""
def __init__(self):
self.mean = numpy.array([0.0, 0.0])
self.covariance = numpy.zeros((2, 2), 'float64')
self.covariance_inverse = numpy.zeros((2, 2), 'float64')
def generate_circular_mask(self, image, radius_ratio=0.4):
"""
This function will generate a circular mask to be applied to the image.
The mask will be true for the pixels contained in a circle centered in the image center,
and with radius equals to radius_ratio * the image's height.
:param image: the (face) image to mask
"""
x_center = image.shape[1] / 2
y_center = image.shape[2] / 2
# arrays with the image coordinates
x = numpy.zeros((image.shape[1], image.shape[2]))
x[:] = range(0, x.shape[1])
y = numpy.zeros((image.shape[2], image.shape[1]))
y[:] = range(0, y.shape[1])
y = numpy.transpose(y)
# translate s.t. the center is the origin
x -= x_center
y -= y_center
# condition to be inside of a circle: x^2 + y^2 < r^2
radius = radius_ratio*image.shape[2]
self.circular_mask = (x**2 + y**2) < (radius**2)
def remove_luma(self, image):
"""
This function remove pixels that are considered as non-skin according to their luma values.
The luma value for all pixels inside a provided circular mask is calculated. Pixels for which the
luma value deviates more than 1.5 * standard deviation are pruned.
:param image: the (face) image to process
"""
# compute the mean and std of luma values on non-masked pixels only
luma = 0.299*image[0, self.circular_mask] + 0.587*image[1, self.circular_mask] + 0.114*image[2, self.circular_mask]
m = numpy.mean(luma)
s = numpy.std(luma)
# apply the filtering to the whole image to get the luma mask
luma = 0.299*image[0, :, :] + 0.587*image[1, :, :] + 0.114*image[2, :, :]
self.luma_mask = numpy.logical_and((luma > (m - 1.5*s)), (luma < (m + 1.5*s)))
def get_gaussian_parameters(self, image):
"""
This function computes the mean and covariance matrix of the skin pixels in the normalised rg colorspace.
Note that only the pixels for which both the circular and the luma mask is 'True' are considered.
:param image: the (face) image out of which skin color characteristics will be extracted.
"""
self.generate_circular_mask(image)
self.remove_luma(image)
mask = numpy.logical_and(self.luma_mask, self.circular_mask)
# get the mean
channel_sum = image[0].astype('float64') + image[1] + image[2]
nonzero_mask = numpy.logical_or(numpy.logical_or(image[0] > 0, image[1] > 0), image[2] > 0)
r = numpy.zeros((image.shape[1], image.shape[2]))
r[nonzero_mask] = image[0, nonzero_mask] / channel_sum[nonzero_mask]
g = numpy.zeros((image.shape[1], image.shape[2]))
g[nonzero_mask] = image[1, nonzero_mask] / channel_sum[nonzero_mask]
self.mean = numpy.array([numpy.mean(r[mask]), numpy.mean(g[mask])])
# get the covariance
r_minus_mean = r[mask] - self.mean[0]
g_minus_mean = g[mask] - self.mean[1]
samples = numpy.vstack((r_minus_mean, g_minus_mean))
samples = samples.T
cov = sum([numpy.outer(s,s) for s in samples])
self.covariance = cov / float(samples.shape[0] - 1)
# store the inverse covariance matrix (no need to recompute)
if numpy.linalg.det(self.covariance) != 0:
self.covariance_inverse = numpy.linalg.inv(self.covariance)
else:
self.covariance_inverse = numpy.zeros_like(self.covariance)
def get_skin_pixels(self, image, threshold):
"""
This function computes the probability of skin-color for each pixel in the image.
the distribution of skin color is considered to be gaussian in the rg colorspace.
:param image: the image to process
:param threshold: the threshold on the probability of a pixel to be of skin color.
"""
skin_map = numpy.zeros((image.shape[1], image.shape[2]), 'float64')
# get the image in rg colorspace
channel_sum = image[0].astype('float64') + image[1] + image[2]
nonzero_mask = numpy.logical_or(numpy.logical_or(image[0] > 0, image[1] > 0), image[2] > 0)
r = numpy.zeros((image.shape[1], image.shape[2]), 'float64')
r[nonzero_mask] = image[0, nonzero_mask] / channel_sum[nonzero_mask]
g = numpy.zeros((image.shape[1], image.shape[2]), 'float64')
g[nonzero_mask] = image[1, nonzero_mask] / channel_sum[nonzero_mask]
# compute the skin probability map
r_minus_mean = r - self.mean[0]
g_minus_mean = g - self.mean[1]
v = numpy.dstack((r_minus_mean, g_minus_mean))
v = v.reshape((r.shape[0]*r.shape[1], 2))
probs = [numpy.dot(k, numpy.dot(self.covariance_inverse, k)) for k in v]
probs = numpy.array(probs).reshape(r.shape)
skin_map = numpy.exp(-0.5 * probs)
return skin_map > threshold
##############################################################################
#
# Copyright (c) 2006 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Bootstrap a buildout-based project
Simply run this script in a directory containing a buildout.cfg.
The script accepts buildout command-line options, so you can
use the -c option to specify an alternate configuration file.
"""
import os
import shutil
import sys
import tempfile
from optparse import OptionParser
tmpeggs = tempfile.mkdtemp()
usage = '''\
[DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options]
Bootstraps a buildout-based project.
Simply run this script in a directory containing a buildout.cfg, using the
Python that you want bin/buildout to use.
Note that by using --find-links to point to local resources, you can keep
this script from going over the network.
'''
parser = OptionParser(usage=usage)
parser.add_option("-v", "--version", help="use a specific zc.buildout version")
parser.add_option("-t", "--accept-buildout-test-releases",
dest='accept_buildout_test_releases',
action="store_true", default=False,
help=("Normally, if you do not specify a --version, the "
"bootstrap script and buildout gets the newest "
"*final* versions of zc.buildout and its recipes and "
"extensions for you. If you use this flag, "
"bootstrap and buildout will get the newest releases "
"even if they are alphas or betas."))
parser.add_option("-c", "--config-file",
help=("Specify the path to the buildout configuration "
"file to be used."))
parser.add_option("-f", "--find-links",
help=("Specify a URL to search for buildout releases"))
parser.add_option("--allow-site-packages",
action="store_true", default=False,
help=("Let bootstrap.py use existing site packages"))
parser.add_option("--setuptools-version",
help="use a specific setuptools version")
options, args = parser.parse_args()
######################################################################
# load/install setuptools
try:
if options.allow_site_packages:
import setuptools
import pkg_resources
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
ez = {}
exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez)
if not options.allow_site_packages:
# ez_setup imports site, which adds site packages
# this will remove them from the path to ensure that incompatible versions
# of setuptools are not in the path
import site
# inside a virtualenv, there is no 'getsitepackages'.
# We can't remove these reliably
if hasattr(site, 'getsitepackages'):
for sitepackage_path in site.getsitepackages():
sys.path[:] = [x for x in sys.path if sitepackage_path not in x]
setup_args = dict(to_dir=tmpeggs, download_delay=0)
if options.setuptools_version is not None:
setup_args['version'] = options.setuptools_version
ez['use_setuptools'](**setup_args)
import setuptools
import pkg_resources
# This does not (always?) update the default working set. We will
# do it.
for path in sys.path:
if path not in pkg_resources.working_set.entries:
pkg_resources.working_set.add_entry(path)
######################################################################
# Install buildout
ws = pkg_resources.working_set
cmd = [sys.executable, '-c',
'from setuptools.command.easy_install import main; main()',
'-mZqNxd', tmpeggs]
find_links = os.environ.get(
'bootstrap-testing-find-links',
options.find_links or
('http://downloads.buildout.org/'
if options.accept_buildout_test_releases else None)
)
if find_links:
cmd.extend(['-f', find_links])
setuptools_path = ws.find(
pkg_resources.Requirement.parse('setuptools')).location
requirement = 'zc.buildout'
version = options.version
if version is None and not options.accept_buildout_test_releases:
# Figure out the most recent final version of zc.buildout.
import setuptools.package_index
_final_parts = '*final-', '*final'
def _final_version(parsed_version):
try:
return not parsed_version.is_prerelease
except AttributeError:
# Older setuptools
for part in parsed_version:
if (part[:1] == '*') and (part not in _final_parts):
return False
return True
index = setuptools.package_index.PackageIndex(
search_path=[setuptools_path])
if find_links:
index.add_find_links((find_links,))
req = pkg_resources.Requirement.parse(requirement)
if index.obtain(req) is not None:
best = []
bestv = None
for dist in index[req.project_name]:
distv = dist.parsed_version
if _final_version(distv):
if bestv is None or distv > bestv:
best = [dist]
bestv = distv
elif distv == bestv:
best.append(dist)
if best:
best.sort()
version = best[-1].version
if version:
requirement = '=='.join((requirement, version))
cmd.append(requirement)
import subprocess
if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=setuptools_path)) != 0:
raise Exception(
"Failed to execute command:\n%s" % repr(cmd)[1:-1])
######################################################################
# Import and run buildout
ws.add_entry(tmpeggs)
ws.require(requirement)
import zc.buildout.buildout
if not [a for a in args if '=' not in a]:
args.append('bootstrap')
# if -c was provided, we push it back into args for buildout' main function
if options.config_file is not None:
args[0:0] = ['-c', options.config_file]
zc.buildout.buildout.main(args)
shutil.rmtree(tmpeggs)
# Guillaume HEUSCH <guillaume.heusch@idiap.ch>
# Wed 30 Mar 14:24:00 CEST 2016
[buildout]
parts = scripts
eggs = bob.ip.skincolorfilter
extensions = bob.buildout
mr.developer
auto-checkout = *
develop = src/bob.extension
src/bob.blitz
src/bob.core
src/bob.io.base
src/bob.io.image
src/bob.ip.base
src/bob.ip.facedetect
.
; options for bob.buildout
debug = true
verbose = true
newest = false
[sources]
bob.extension = git https://github.com/bioidiap/bob.extension
bob.blitz = git https://github.com/bioidiap/bob.blitz
bob.core = git https://github.com/bioidiap/bob.core
bob.io.base = git https://github.com/bioidiap/bob.io.base
bob.io.image = git https://github.com/bioidiap/bob.io.image
bob.ip.base = git https://github.com/bioidiap/bob.ip.base
bob.ip.facedetect = git https://github.com/bioidiap/bob.ip.facedetect
[scripts]
recipe = bob.buildout:scripts
dependent-scripts = true
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Andre Anjos <andre.anjos@idiap.ch>
# Mon 13 Aug 2012 12:38:15 CEST
#
# Copyright (C) 2011-2014 Idiap Research Institute, Martigny, Switzerland
import os
import sys
import glob
import pkg_resources
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.pngmath',
'sphinx.ext.ifconfig',
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
]
# The viewcode extension appeared only on Sphinx >= 1.0.0
import sphinx
if sphinx.__version__ >= "1.0":
extensions.append('sphinx.ext.viewcode')
# Always includes todos
todo_include_todos = True
# If we are on OSX, the 'dvipng' path maybe different
dvipng_osx = '/opt/local/libexec/texlive/binaries/dvipng'
if os.path.exists(dvipng_osx): pngmath_dvipng = dvipng_osx
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Bob Example Project'
import time
copyright = u'%s, Idiap Research Institute' % time.strftime('%Y')
# Grab the setup entry
distribution = pkg_resources.require('bob.example.project')[0]
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = distribution.version
# The full version, including alpha/beta/rc tags.
release = distribution.version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
#exclude_patterns = ['**/links.rst']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
if sphinx.__version__ >= "1.0":
html_theme = 'nature'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = 'bob'
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = ''
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
html_favicon = ''
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
#html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'bob_example_project_doc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
latex_paper_size = 'a4'
# The font size ('10pt', '11pt' or '12pt').
latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'bob_example_project.tex', u'Bob',
u'Biometrics Group, Idiap Research Institute', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
latex_logo = ''