Exemplo n.º 1
0
def quality(ctx, flake8=True, rstlint=True):
    """
    Checks the codebase with *Flake8* and lints various *restructuredText*
    files with *rst-lint*.

    Parameters
    ----------
    ctx : invoke.context.Context
        Context.
    flake8 : bool, optional
        Whether to check the codebase with *Flake8*.
    rstlint : bool, optional
        Whether to lint various *restructuredText* files with *rst-lint*.

    Returns
    -------
    bool
        Task success.
    """

    if flake8:
        message_box('Checking codebase with "Flake8"...')
        ctx.run('flake8 {0} --exclude=examples'.format(PYTHON_PACKAGE_NAME))

    if rstlint:
        message_box('Linting "README.rst" file...')
        ctx.run('rst-lint README.rst')
Exemplo n.º 2
0
def tests(ctx, nose=True):
    """
    Runs the unit tests with *Nose* or *Pytest*.

    Parameters
    ----------
    ctx : invoke.context.Context
        Context.
    nose : bool, optional
        Whether to use *Nose* or *Pytest*.

    Returns
    -------
    bool
        Task success.
    """

    if nose:
        message_box('Running "Nosetests"...')
        ctx.run(
            'nosetests --with-doctest --with-coverage --cover-package={0} {0}'.
            format(PYTHON_PACKAGE_NAME))
    else:
        message_box('Running "Pytest"...')
        ctx.run('pytest -W ignore')
Exemplo n.º 3
0
def clean(ctx, docs=True, bytecode=False):
    """
    Cleans the project.

    Parameters
    ----------
    ctx : invoke.context.Context
        Context.
    docs : bool, optional
        Whether to clean the *docs* directory.
    bytecode : bool, optional
        Whether to clean the bytecode files, e.g. *.pyc* files.

    Returns
    -------
    bool
        Task success.
    """
    message_box('Cleaning project...')

    patterns = ['build', '*.egg-info', 'dist']

    if docs:
        patterns.append('docs/_build')
        patterns.append('docs/generated')

    if bytecode:
        patterns.append('**/*.pyc')

    for pattern in patterns:
        ctx.run("rm -rf {}".format(pattern))
Exemplo n.º 4
0
def examples(ctx, plots=False):
    """
    Runs the examples.

    Parameters
    ----------
    ctx : invoke.context.Context
        Context.
    plots : bool, optional
        Whether to skip or only run the plotting examples: This a mutually
        exclusive switch.

    Returns
    -------
    bool
        Task success.
    """

    message_box('Running examples...')

    for root, _dirnames, filenames in os.walk(
            os.path.join(PYTHON_PACKAGE_NAME, 'examples')):
        for filename in fnmatch.filter(filenames, '*.py'):
            if not plots and ('plotting' in root or
                              'examples_interpolation' in filename or
                              'examples_contrast' in filename):
                continue

            if plots and ('plotting' not in root and
                          'examples_interpolation' not in filename and
                          'examples_contrast' not in filename):
                continue

            ctx.run('python {0}'.format(os.path.join(root, filename)))
    def describe_actions_action(self):
        """
        Defines the slot triggered by the *describe_actions* action.

        Returns
        -------
        bool
            Definition success.
        """

        actions = ['Actions & Shortcuts\n']
        for _name, action in sorted(self.canvas.actions.items()):
            if action.sequence.modifiers:
                sequence = '{0} + {1}'.format(' + '.join(
                    action.sequence.modifiers), action.sequence.key)
            else:
                sequence = '{0}'.format(action.sequence.key)
            actions.append('- {0}: {1}'.format(action.description, sequence))

        actions = '\n'.join(actions)

        self.write('{0}'.format(actions))

        message_box('{0}'.format(actions))

        return True
    def describe_analysis_state_action(self):
        """
        Defines the slot triggered by the *describe_analysis_state* action.

        Returns
        -------
        bool
            Definition success.
        """

        state = ['Analysis State\n']

        state.append('- Input image: {0}'.format(self.canvas.image_path))
        state.append('- Input RGB colourspace: {0}'.format(
            self.canvas.input_colourspace))
        state.append('- Input OECF: {0}'.format(self.canvas.input_oecf))
        state.append('- Input linearity: {0}'.format(self.canvas.input_linear))
        state.append('- Reference colourspace: {0}'.format(
            self.canvas.reference_colourspace))
        state.append('- Correlate RGB colourspace: {0}'.format(
            self.canvas.correlate_colourspace))
        state.append('- Blacks Clamped: {0}'.format(self.canvas.clamp_blacks))
        state.append('- Whites Clamped: {0}'.format(self.canvas.clamp_whites))
        state = '\n'.join(state)

        self.write('{0}'.format(state))

        message_box('{0}'.format(state))

        return True
Exemplo n.º 7
0
def preflight(ctx):
    """
    Performs the preflight tasks, i.e. *formatting*, *tests*, *quality*, and
    *examples*.

    Parameters
    ----------
    ctx : invoke.context.Context
        Context.

    Returns
    -------
    bool
        Task success.
    """

    message_box('Finishing "Preflight"...')
Exemplo n.º 8
0
def sha256(ctx):
    """
    Computes the project *Pypi* package *sha256* with *OpenSSL*.

    Parameters
    ----------
    ctx : invoke.context.Context
        Context.

    Returns
    -------
    bool
        Task success.
    """

    message_box('Computing "sha256"...')
    with ctx.cd('dist'):
        ctx.run('openssl sha256 {0}-*.tar.gz'.format(PYPI_PACKAGE_NAME))
Exemplo n.º 9
0
def tag(ctx):
    """
    Tags the repository according to defined version using *git-flow*.

    Parameters
    ----------
    ctx : invoke.context.Context
        Context.

    Returns
    -------
    bool
        Task success.
    """

    message_box('Tagging...')
    result = ctx.run('git rev-parse --abbrev-ref HEAD', hide='both')
    assert result.stdout.strip() == 'develop', (
        'Are you still on a feature or master branch?')

    with open(os.path.join(PYTHON_PACKAGE_NAME, '__init__.py')) as file_handle:
        file_content = file_handle.read()
        major_version = re.search("__major_version__\s+=\s+'(.*)'",
                                  file_content).group(1)
        minor_version = re.search("__minor_version__\s+=\s+'(.*)'",
                                  file_content).group(1)
        change_version = re.search("__change_version__\s+=\s+'(.*)'",
                                   file_content).group(1)

        version = '.'.join((major_version, minor_version, change_version))

        result = ctx.run('git ls-remote --tags upstream', hide='both')
        remote_tags = result.stdout.strip().split('\n')
        tags = set()
        for remote_tag in remote_tags:
            tags.add(
                remote_tag.split('refs/tags/')[1].replace('refs/tags/', '^{}'))
        tags = sorted(list(tags))
        assert 'v{0}'.format(version) not in tags, (
            'A "{0}" "v{1}" tag already exists in remote repository!'.format(
                PYTHON_PACKAGE_NAME, version))

        ctx.run('git flow release start v{0}'.format(version))
        ctx.run('git flow release finish v{0}'.format(version))
Exemplo n.º 10
0
def todo(ctx):
    """
    Export the TODO items.

    Parameters
    ----------
    ctx : invoke.context.Context
        Context.

    Returns
    -------
    bool
        Task success.
    """

    message_box('Exporting "TODO" items...')

    with ctx.cd('utilities'):
        ctx.run('./export_todo.py')
Exemplo n.º 11
0
def build(ctx):
    """
    Builds the project and runs dependency tasks, i.e. *docs*, *todo*, and
    *preflight*.

    Parameters
    ----------
    ctx : invoke.context.Context
        Context.

    Returns
    -------
    bool
        Task success.
    """

    message_box('Building...')
    ctx.run('python setup.py sdist')
    ctx.run('python setup.py bdist_wheel --universal')
Exemplo n.º 12
0
def release(ctx):
    """
    Releases the project to *Pypi* with *Twine*.

    Parameters
    ----------
    ctx : invoke.context.Context
        Context.

    Returns
    -------
    bool
        Task success.
    """

    message_box('Releasing...')
    with ctx.cd('dist'):
        ctx.run('twine upload *.tar.gz')
        ctx.run('twine upload *.whl')
Exemplo n.º 13
0
def docs(ctx, plots=True, html=True, pdf=True):
    """
    Builds the documentation.

    Parameters
    ----------
    ctx : invoke.context.Context
        Context.
    plots : bool, optional
        Whether to generate the documentation plots.
    html : bool, optional
        Whether to build the *HTML* documentation.
    pdf : bool, optional
        Whether to build the *PDF* documentation.

    Returns
    -------
    bool
        Task success.
    """

    if plots:
        temporary_directory = tempfile.mkdtemp()
        test_directory = os.path.join('docs', '_static')
        reference_directory = os.path.join(temporary_directory, '_static')
        try:
            shutil.copytree(test_directory, reference_directory)
            similar_plots = []
            with ctx.cd('utilities'):
                message_box('Generating plots...')
                ctx.run('./generate_plots.py')

                png_files = glob.glob('{0}/*.png'.format(reference_directory))
                for reference_png_file in png_files:
                    test_png_file = os.path.join(
                        test_directory, os.path.basename(reference_png_file))
                    psnr = metric_psnr(
                        read_image(str(reference_png_file))[::3, ::3],
                        read_image(str(test_png_file))[::3, ::3])
                    if psnr > 70:
                        similar_plots.append(test_png_file)
            with ctx.cd('docs/_static'):
                for similar_plot in similar_plots:
                    ctx.run('git checkout -- {0}'.format(
                        os.path.basename(similar_plot)))
        finally:
            shutil.rmtree(temporary_directory)

    with ctx.prefix('export COLOUR_SCIENCE_DOCUMENTATION_BUILD=True'):
        with ctx.cd('docs'):
            if html:
                message_box('Building "HTML" documentation...')
                ctx.run('make html')

            if pdf:
                message_box('Building "PDF" documentation...')
                ctx.run('make latexpdf')
Exemplo n.º 14
0
def formatting(ctx, yapf=False, asciify=True, bibtex=True):
    """
    Formats the codebase with *Yapf* and converts unicode characters to ASCII.

    Parameters
    ----------
    ctx : invoke.context.Context
        Context.
    yapf : bool, optional
        Whether to format the codebase with *Yapf*.
    asciify : bool, optional
        Whether to convert unicode characters to ASCII.
    bibtex : bool, optional
        Whether to cleanup the *BibTeX* file.

    Returns
    -------
    bool
        Task success.
    """

    if yapf:
        message_box('Formatting codebase with "Yapf"...')
        ctx.run('yapf -p -i -r --exclude \'.git\' .')

    if asciify:
        message_box('Converting unicode characters to ASCII...')
        with ctx.cd('utilities'):
            ctx.run('./unicode_to_ascii.py')

    if bibtex and sys.version_info[:2] >= (3, 2):
        message_box('Cleaning up "BibTeX" file...')
        bibtex_path = BIBLIOGRAPHY_NAME
        with open(bibtex_path) as bibtex_file:
            bibtex = biblib.bib.Parser().parse(
                bibtex_file.read()).get_entries()

        for entry in sorted(bibtex.values(), key=lambda x: x.key):
            try:
                del entry['file']
            except KeyError:
                pass
            for key, value in entry.items():
                entry[key] = re.sub('(?<!\\\\)\\&', '\\&', value)

        with open(bibtex_path, 'w') as bibtex_file:
            for entry in bibtex.values():
                bibtex_file.write(entry.to_bib())
                bibtex_file.write('\n')
Exemplo n.º 15
0
# -*- coding: utf-8 -*-
"""
Showcases input / output *IES TM-27-14* spectral data XML files related
examples.
"""

import os

import colour
from colour.utilities import message_box

RESOURCES_DIRECTORY = os.path.join(os.path.dirname(__file__), 'resources')

message_box('"IES TM-27-14" Spectral Data "XML" File IO')

message_box('Reading spectral data from "IES TM-27-14" "XML" file.')
spd = colour.IES_TM2714_Spd(
    os.path.join(RESOURCES_DIRECTORY, 'TM27 Sample Spectral Data.spdx'))
spd.read()
print(spd)

print('\n')

message_box('"IES TM-27-14" spectral data "XML" file header:')
print('Manufacturer: {0}'.format(spd.header.manufacturer))
print('Catalog Number: {0}'.format(spd.header.catalog_number))
print('Description: {0}'.format(spd.header.description))
print('Document Creator: {0}'.format(spd.header.document_creator))
print('Unique Identifier: {0}'.format(spd.header.unique_identifier))
print('Measurement Equipment: {0}'.format(spd.header.measurement_equipment))
print('Laboratory: {0}'.format(spd.header.laboratory))
Exemplo n.º 16
0
def describe_conversion_path(
    source: str,
    target: str,
    mode: Union[Literal["Short", "Long", "Extended"], str] = "Short",
    width: Integer = 79,
    padding: Integer = 3,
    print_callable: Callable = print,
    **kwargs: Any,
):
    """
    Describe the conversion path from source colour representation to target
    colour representation using the automatic colour conversion graph.

    Parameters
    ----------
    source
        Source colour representation, i.e. the source node in the automatic
        colour conversion graph.
    target
        Target colour representation, i.e. the target node in the automatic
        colour conversion graph.
    mode
        Verbose mode: *Short* describes the conversion path, *Long* provides
        details about the arguments, definitions signatures and output values,
        *Extended* appends the definitions' documentation.
    width
        Message box width.
    padding
        Padding on each side of the message.
    print_callable
        Callable used to print the message box.

    Other Parameters
    ----------------
    kwargs
        {:func:`colour.convert`},
        See the documentation of the previously listed definition.

    Examples
    --------
    >>> describe_conversion_path('Spectral Distribution', 'sRGB', width=75)
    ===========================================================================
    *                                                                         *
    *   [ Conversion Path ]                                                   *
    *                                                                         *
    *   "sd_to_XYZ" --> "XYZ_to_sRGB"                                         *
    *                                                                         *
    ===========================================================================
    """

    try:  # pragma: no cover
        signature_inspection = inspect.signature
    except AttributeError:  # pragma: no cover
        signature_inspection = inspect.getargspec  # type: ignore[assignment]

    source, target = source.lower(), target.lower()
    mode = validate_method(
        mode,
        ["Short", "Long", "Extended"],
        '"{0}" mode is invalid, it must be one of {1}!',
    )

    width = (79 + 2 + 2 * 3 - 4) if mode == "extended" else width

    conversion_path = _conversion_path(source, target)

    message_box(
        "[ Conversion Path ]\n\n{}".format(" --> ".join([
            f'"{_lower_order_function(conversion_function).__name__}"'
            for conversion_function in conversion_path
        ])),
        width,
        padding,
        print_callable,
    )

    for conversion_function in conversion_path:
        conversion_function_name = _lower_order_function(
            conversion_function).__name__

        # Filtering compatible keyword arguments passed directly and
        # irrespective of any conversion function name.
        filtered_kwargs = filter_kwargs(conversion_function, **kwargs)

        # Filtering keyword arguments passed as dictionary with the
        # conversion function name.
        filtered_kwargs.update(kwargs.get(conversion_function_name, {}))

        return_value = filtered_kwargs.pop("return", None)

        if mode in ("long", "extended"):
            signature = pformat(
                signature_inspection(
                    _lower_order_function(conversion_function)))
            message = (
                f'[ "{_lower_order_function(conversion_function).__name__}" ]\n\n'
                f"[ Signature ]\n\n"
                f"{signature}")

            if filtered_kwargs:
                message += (
                    f"\n\n[ Filtered Arguments ]\n\n{pformat(filtered_kwargs)}"
                )

            if mode in ("extended", ):
                docstring = textwrap.dedent(
                    str(_lower_order_function(
                        conversion_function).__doc__)).strip()
                message += f"\n\n[ Documentation ]\n\n {docstring}"

            if return_value is not None:
                message += f"\n\n[ Conversion Output ]\n\n{return_value}"

            message_box(message, width, padding, print_callable)
Exemplo n.º 17
0
# -*- coding: utf-8 -*-
"""
Showcases interpolation computations.
"""

import matplotlib.pyplot as plt
import numpy as np
import os

import colour
from colour.plotting import render
from colour.utilities import message_box

message_box('Interpolation Computations')

message_box(('Comparing "Sprague (1880)" and "Cubic Spline" recommended '
             'interpolation methods to "Pchip" method.'))

uniform_sd_data = {
    340: 0.0000,
    360: 0.0000,
    380: 0.0000,
    400: 0.0641,
    420: 0.0645,
    440: 0.0562,
    460: 0.0537,
    480: 0.0559,
    500: 0.0651,
    520: 0.0705,
    540: 0.0772,
    560: 0.0870,
Exemplo n.º 18
0
"""Showcases Look Up Table (LUT) data related examples."""

import numpy as np
import os

import colour
from colour.utilities import message_box

RESOURCES_DIRECTORY = os.path.join(os.path.dirname(__file__), "..", "..", "io",
                                   "luts", "tests", "resources")

message_box("Look Up Table (LUT) Data")

message_box('Reading a "Cinespace" ".csp" 3D LUT with Shaper file.')
path = os.path.join(RESOURCES_DIRECTORY, "cinespace",
                    "Three_Dimensional_Table_With_Shaper.csp")
print(colour.io.read_LUT_Cinespace(path))
print("\n")
print(colour.read_LUT(path))

print("\n")

message_box('Reading an "Iridas" ".cube" 3x1D LUT file.')
path = os.path.join(RESOURCES_DIRECTORY, "iridas_cube",
                    "ACES_Proxy_10_to_ACES.cube")
print(colour.io.read_LUT_IridasCube(path))
print("\n")
print(colour.read_LUT(path))

print("\n")
Exemplo n.º 19
0
def build(ctx):
    """
    Builds the project and runs dependency tasks, i.e. *docs*, *todo*, and
    *preflight*.

    Parameters
    ----------
    ctx : invoke.context.Context
        Context.

    Returns
    -------
    bool
        Task success.
    """

    message_box('Building...')
    if 'modified:   pyproject.toml' in ctx.run('git status').stdout:
        raise RuntimeError(
            'Please commit your changes to the "pyproject.toml" file!')

    pyproject_content = toml.load('pyproject.toml')
    pyproject_content['tool']['poetry']['name'] = PYPI_PACKAGE_NAME
    pyproject_content['tool']['poetry']['packages'] = [{
        'include': PYTHON_PACKAGE_NAME,
        'from': '.'
    }]
    with open('pyproject.toml', 'w') as pyproject_file:
        toml.dump(pyproject_content, pyproject_file)

    if 'modified:   README.rst' in ctx.run('git status').stdout:
        raise RuntimeError(
            'Please commit your changes to the "README.rst" file!')

    with open('README.rst', 'r') as readme_file:
        readme_content = readme_file.read()

    with open('README.rst', 'w') as readme_file:
        readme_file.write(
            re.sub(
                ('(\\.\\. begin-trim-long-description.*?'
                 '\\.\\. end-trim-long-description)'),
                '',
                readme_content,
                flags=re.DOTALL))

    ctx.run('poetry build')
    ctx.run('git checkout -- pyproject.toml')
    ctx.run('git checkout -- README.rst')

    with ctx.cd('dist'):
        ctx.run('tar -xvf {0}-{1}.tar.gz'.format(PYPI_PACKAGE_NAME,
                                                 APPLICATION_VERSION))
        ctx.run('cp {0}-{1}/setup.py ../'.format(PYPI_PACKAGE_NAME,
                                                 APPLICATION_VERSION))

        ctx.run('rm -rf {0}-{1}'.format(PYPI_PACKAGE_NAME,
                                        APPLICATION_VERSION))

    with open('setup.py') as setup_file:
        source = setup_file.read()

    setup_kwargs = []

    def sub_callable(match):
        setup_kwargs.append(match)

        return ''

    template = """
setup({0}
)
"""

    source = re.sub('from setuptools import setup',
                    'import codecs\nfrom setuptools import setup', source)
    source = re.sub(
        'setup_kwargs = {(.*)}.*setup\\(\\*\\*setup_kwargs\\)',
        sub_callable,
        source,
        flags=re.DOTALL)[:-2]
    setup_kwargs = setup_kwargs[0].group(1).splitlines()
    for i, line in enumerate(setup_kwargs):
        setup_kwargs[i] = re.sub('^\\s*(\'(\\w+)\':\\s?)', '    \\2=', line)
        if setup_kwargs[i].strip().startswith('long_description'):
            setup_kwargs[i] = ('    long_description='
                               'codecs.open(\'README.rst\', encoding=\'utf8\')'
                               '.read(),')

    source += template.format('\n'.join(setup_kwargs))

    with open('setup.py', 'w') as setup_file:
        setup_file.write(source)

    ctx.run('twine check dist/*')
Exemplo n.º 20
0
"""Showcases *Luminance* computations."""

import colour

from colour.utilities import message_box

message_box('"Luminance" Computations')

V = 4.08244375
message_box(
    f'Computing "luminance" using "Newhall, Nickerson, and Judd (1943)" '
    f'method for given "Munsell" value:\n\n\t{V}')
print(colour.luminance(V, method="Newhall 1943"))
print(colour.colorimetry.luminance_Newhall1943(V))

print("\n")

L = 41.527875844653451
message_box(f'Computing "luminance" using "CIE 1976" method for given '
            f'"Lightness":\n\n\t{L}')
print(colour.luminance(L))
print(colour.colorimetry.luminance_CIE1976(L))

print("\n")

L = 31.996390226262736
message_box(
    f'Computing "luminance" using "Fairchild and Wyble (2010)" method for '
    f'given "Lightness":\n\n\t{L}')
print(colour.luminance(L, method="Fairchild 2010") * 100)
print(colour.colorimetry.luminance_Fairchild2010(L) * 100)
Exemplo n.º 21
0
"""Showcases colour rendition charts computations."""

import numpy as np
from pprint import pprint

import colour
from colour.utilities import message_box

message_box("Colour Rendition Charts Computations")

message_box("Colour rendition charts chromaticity coordinates dataset.")
pprint(sorted(colour.CCS_COLOURCHECKERS.keys()))

print("\n")

message_box("Colour rendition charts spectral distributions dataset.")
pprint(colour.SDS_COLOURCHECKERS.keys())

print("\n")

message_box(
    '"ColorChecker 2005" colour rendition chart chromaticity coordinates data:\n\n'
    '\t("Patch Number", "Patch Name", "xyY")'
)
name, data, illuminant = colour.CCS_COLOURCHECKERS["ColorChecker 2005"]
for name, xyY in data.items():
    print(name, xyY)

print("\n")

message_box(
"""Showcases optical phenomena plotting examples."""

from colour.phenomena import sd_rayleigh_scattering
from colour.plotting import (
    colour_style,
    plot_multi_sds,
    plot_single_sd_rayleigh_scattering,
    plot_the_blue_sky,
)
from colour.utilities import message_box

message_box("Optical Phenomena Plots")

colour_style()

message_box('Plotting a single "Rayleigh" scattering spectral "distribution."')
plot_single_sd_rayleigh_scattering()

print("\n")

message_box(
    'Comparing multiple "Rayleigh" scattering spectral distributions with '
    "different CO_2 concentrations.")
name_template = "Rayleigh Scattering - CO2: {0} ppm"
sds_rayleigh = []
for ppm in (0, 50, 300):
    sd_rayleigh = sd_rayleigh_scattering(CO2_concentration=ppm)
    sd_rayleigh.name = name_template.format(ppm)
    sds_rayleigh.append(sd_rayleigh)
plot_multi_sds(
    sds_rayleigh,
Exemplo n.º 23
0
# -*- coding: utf-8 -*-
"""
Showcases colour spectrum computations.
"""

import numpy as np

import colour
from colour.utilities import message_box

message_box('Spectrum Computations')

sample_sd_data = {
    380: 0.048,
    385: 0.051,
    390: 0.055,
    395: 0.060,
    400: 0.065,
    405: 0.068,
    410: 0.068,
    415: 0.067,
    420: 0.064,
    425: 0.062,
    430: 0.059,
    435: 0.057,
    440: 0.055,
    445: 0.054,
    450: 0.053,
    455: 0.053,
    460: 0.052,
    465: 0.052,
Exemplo n.º 24
0
# -*- coding: utf-8 -*-
"""
Showcases overall *Colour* examples.
"""

import numpy as np
import warnings

import colour
from colour.utilities import (message_box, warning, runtime_warning,
                              usage_warning)

message_box('Filter "Colour" Warnings')

warning('This is a first warning and it can be filtered!')

colour.filter_warnings()

warning('This is a second warning and it has been filtered!')

colour.filter_warnings(False)

warning('This is a third warning and it has not been filtered!')

message_box('All Python can be filtered by setting the '
            '"colour.filter_warnings" definition "python_warnings" '
            'argument.')

warnings.warn('This is a fourth warning and it has not been filtered!')

colour.filter_warnings(python_warnings=False)
Exemplo n.º 25
0
def build(ctx: Context):
    """Build the project and runs dependency tasks, i.e., *docs*, *todo*, and
    *preflight*.

    Parameters
    ----------
    ctx
        Context.
    """

    message_box("Building...")
    ctx.run("poetry build")

    with ctx.cd("dist"):
        ctx.run(f"tar -xvf {PYPI_PACKAGE_NAME}-{APPLICATION_VERSION}.tar.gz")
        ctx.run(f"cp {PYPI_PACKAGE_NAME}-{APPLICATION_VERSION}/setup.py ../")

        ctx.run(f"rm -rf {PYPI_PACKAGE_NAME}-{APPLICATION_VERSION}")

    with open("setup.py") as setup_file:
        source = setup_file.read()

    setup_kwargs = []

    def sub_callable(match):
        setup_kwargs.append(match)

        return ""

    template = """
setup({0}
)
"""

    source = re.sub(
        "from setuptools import setup",
        ('"""\n'
         "Colour - Checker Detection - Setup\n"
         "==================================\n"
         '"""\n\n'
         "import codecs\n"
         "from setuptools import setup"),
        source,
    )
    source = re.sub(
        "setup_kwargs = {(.*)}.*setup\\(\\*\\*setup_kwargs\\)",
        sub_callable,
        source,
        flags=re.DOTALL,
    )[:-2]
    setup_kwargs = setup_kwargs[0].group(1).splitlines()
    for i, line in enumerate(setup_kwargs):
        setup_kwargs[i] = re.sub("^\\s*('(\\w+)':\\s?)", "    \\2=", line)
        if setup_kwargs[i].strip().startswith("long_description"):
            setup_kwargs[i] = ("    long_description="
                               "codecs.open('README.rst', encoding='utf8')"
                               ".read(),")

    source += template.format("\n".join(setup_kwargs))

    with open("setup.py", "w") as setup_file:
        setup_file.write(source)

    ctx.run("poetry run pre-commit run --files setup.py || true")

    ctx.run("twine check dist/*")
Exemplo n.º 26
0
# -*- coding: utf-8 -*-
"""
Showcases *LLAB(l:c)* colour appearance model computations.
"""

import numpy as np

import colour
from colour.appearance.llab import LLAB_ReferenceSpecification
from colour.utilities import message_box

message_box('"LLAB(l:c)" Colour Appearance Model Computations')

XYZ = np.array([19.01, 20.00, 21.78])
XYZ_0 = np.array([95.05, 100.00, 108.88])
Y_b = 20.0
L = 318.31
surround = colour.LLAB_VIEWING_CONDITIONS['ref_average_4_minus']
message_box(
    ('Converting to "LLAB(l:c)" colour appearance model '
     'specification using given parameters:\n'
     '\n\tXYZ: {0}\n\tXYZ_0: {1}\n\tY_b: {2}\n\tL: {3}'
     '\n\tsurround: {4}\n\n'
     'Warning: The input domain of that definition is non standard!'.format(
         XYZ, XYZ_0, Y_b, L, surround)))
specification = colour.XYZ_to_LLAB(XYZ, XYZ_0, Y_b, L, surround)
print(specification)

print('\n')

message_box(('Broadcasting current output "LLAB(l:c)" colour appearance '
Exemplo n.º 27
0
# -*- coding: utf-8 -*-
"""
Showcases *Photometry* computations.
"""

import colour
from colour.utilities import message_box

message_box('"Photometry" Computations')

spd = colour.LIGHT_SOURCES_RELATIVE_SPDS['Neodimium Incandescent']
message_box(('Computing "Luminous Flux" for given spectral power '
             'distribution:\n'
             '\n\t{0}'.format(spd.name)))
print(colour.luminous_flux(spd))

print('\n')

message_box(('Computing "Luminous Efficiency" for given spectral power '
             'distribution:\n'
             '\n\t{0}'.format(spd.name)))
print(colour.luminous_efficiency(spd))

print('\n')

message_box(('Computing "Luminous Efficacy" for given spectral power '
             'distribution:\n'
             '\n\t{0}'.format(spd.name)))
print(colour.luminous_efficacy(spd))
Exemplo n.º 28
0
# -*- coding: utf-8 -*-
"""
Showcases hexadecimal computations.
"""

import numpy as np

import colour.notation.hexadecimal
from colour.utilities import message_box

message_box('Hexadecimal Computations')

RGB = np.array([0.45620519, 0.03081071, 0.04091952])
message_box(('Converting to "hexadecimal" representation from given "RGB" '
             'colourspace values:\n'
             '\n\t{0}'.format(RGB)))
print(colour.notation.hexadecimal.RGB_to_HEX(RGB))

print('\n')

hex_triplet = '#74070a'
message_box(('Converting to "RGB" colourspace from given "hexadecimal" '
             'representation:\n'
             '\n\t{0}'.format(hex_triplet)))
print(colour.notation.hexadecimal.HEX_to_RGB(hex_triplet))
Exemplo n.º 29
0
"""Showcases *Prismatic* colourspace computations."""

import numpy as np

import colour
from colour.utilities import message_box

message_box('"Prismatic" Colourspace Computations')

RGB = np.array([0.25, 0.50, 0.75])
message_box(
    f'Converting from the "RGB" colourspace to the "Prismatic" colourspace '
    f'given "RGB" values:\n\n\t{RGB}')
print(colour.RGB_to_Prismatic(RGB))

print("\n")

Lrgb = np.array([0.7500000, 0.1666667, 0.3333333, 0.5000000])
message_box(
    f'Converting from the "Prismatic" colourspace to the "RGB" colourspace '
    f'given "Lrgb" values:\n\n\t{Lrgb}')
print(colour.Prismatic_to_RGB(Lrgb))

print("\n")

message_box(
    f'Applying 50% desaturation in the "Prismatic" colourspace to the given '
    f'"RGB" values:\n\n\t{RGB}')
saturation = 0.5
Lrgb = colour.RGB_to_Prismatic(RGB)
Lrgb[..., 1:] = 1.0 / 3.0 + saturation * (Lrgb[..., 1:] - 1.0 / 3.0)
Exemplo n.º 30
0
# -*- coding: utf-8 -*-
"""
Showcases *RGB* *colourspaces* computations.
"""

import numpy as np
from pprint import pprint

import colour
from colour.utilities import message_box

message_box('"RGB" Colourspaces Computations')

message_box('"RGB" colourspaces dataset.')
pprint(sorted(colour.RGB_COLOURSPACES.keys()))

print('\n')

message_box('"ACES2065-1" colourspaces data.')
colourspace = colour.RGB_COLOURSPACES['ACES2065-1']
print('Name:\n"{0}"'.format(colourspace.name))
print('\nPrimaries:\n{0}'.format(colourspace.primaries))
print(('\nNormalised primary matrix to "CIE XYZ" '
       'tristimulus values:\n{0}').format(colourspace.RGB_to_XYZ_matrix))
print('\nNormalised primary matrix to "ACES2065-1":\n{0}'.format(
    colourspace.XYZ_to_RGB_matrix))
print('\nOpto-electronic transfer function from '
      'linear to colourspace:\n{0}'.format(colourspace.encoding_cctf))
print('\nElectro-optical transfer function from '
      'colourspace to linear:\n{0}'.format(colourspace.decoding_cctf))
Exemplo n.º 31
0
# -*- coding: utf-8 -*-
"""
Showcases common plotting examples.
"""

from colour.plotting import (ColourSwatch, colour_plotting_defaults,
                             multi_colour_swatches_plot,
                             single_colour_swatch_plot)
from colour.utilities import message_box

message_box('Common Plots')

colour_plotting_defaults()

message_box('Plotting a single colour.')
single_colour_swatch_plot(ColourSwatch('Neutral 5 (.70 D)',
                                       RGB=(0.32315746, 0.32983556,
                                            0.33640183)),
                          text_size=32)

print('\n')

message_box('Plotting multiple colours.')
multi_colour_swatches_plot(
    (ColourSwatch('Dark Skin', RGB=(0.45293517, 0.31732158, 0.26414773)),
     ColourSwatch('Light Skin', RGB=(0.77875824, 0.57726450, 0.50453169))),
    spacing=0,
    text_size=32)
# -*- coding: utf-8 -*-
"""
Showcases colour component transfer functions (CCTF) relates computations.
"""

import colour
from colour.utilities import message_box

message_box('Colour Component Transfer Functions (CCTF) Computations')

C = 18 / 100

message_box(('Encoding to video component signal value using "BT.709" OETF '
             'and given linear-light value:\n'
             '\n\t{0}'.format(C)))
print(colour.oetf(C, function='ITU-R BT.709'))
print(colour.models.oetf_BT709(C))

print('\n')

N = 0.40900773
message_box(('Decoding to linear-light value using "BT.1886" EOTF and given '
             ' video component signal value:\n'
             '\n\t{0}'.format(N)))
print(colour.eotf(N, function='ITU-R BT.1886'))
print(colour.models.eotf_BT1886(N))

print('\n')

message_box(('Encoding to "Cineon" using given linear-light value:\n'
             '\n\t{0}'.format(C)))
Exemplo n.º 33
0
# -*- coding: utf-8 -*-
"""
Showcases *YCoCg* *colour encoding* computations.
"""

import numpy as np

import colour
from colour.utilities import message_box

message_box('"YCoCg" Colour Encoding Computations')

RGB = np.array([0.45620519, 0.03081071, 0.04091952])
message_box(('Converting to "YCoCg" colour encoding from given "RGB" '
             'colourspace values:\n'
             '\n\t{0}'.format(RGB)))
print(colour.RGB_to_YCoCg(RGB))

print('\n')

YCoCg = np.array([0.13968653, 0.20764283, -0.10887582])
message_box(
    ('Converting to "RGB" colourspace values from "YCoCg" colour encoding '
     'values:\n'
     '\n\t{0}'.format(YCoCg)))
print(colour.YCoCg_to_RGB(YCoCg))
Exemplo n.º 34
0
# -*- coding: utf-8 -*-
"""
Showcases *CAM16* colour appearance model computations.
"""

import numpy as np

import colour
from colour.utilities import message_box

message_box('"CAM16" Colour Appearance Model Computations')

XYZ = np.array([19.01, 20.00, 21.78])
XYZ_w = np.array([95.05, 100.00, 108.88])
L_A = 318.31
Y_b = 20.0
surround = colour.CAM16_VIEWING_CONDITIONS['Average']
message_box(
    ('Converting to "CAM16" colour appearance model specification '
     'using given parameters:\n'
     '\n\tXYZ: {0}\n\tXYZ_w: {1}\n\tL_A: {2}\n\tY_b: {3}'
     '\n\tSurround: {4}\n\n'
     'Warning: The input domain of that definition is non standard!').format(
         XYZ, XYZ_w, L_A, Y_b, surround))
specification = colour.XYZ_to_CAM16(XYZ, XYZ_w, L_A, Y_b, surround)
print(specification)

print('\n')

J = 41.73120791
C = 0.10335574
Exemplo n.º 35
0
# -*- coding: utf-8 -*-
"""
Showcases colour correction computations.
"""

import numpy as np
import colour
from colour.utilities import message_box

message_box('Colour Correction Computations')

M_T = np.array([
    [0.17290600, 0.08205715, 0.05711951],
    [0.56807350, 0.29250361, 0.21942000],
    [0.10437166, 0.19656122, 0.32946697],
    [0.10089156, 0.14839029, 0.05324779],
    [0.22306044, 0.21697008, 0.43151034],
    [0.10718115, 0.51351274, 0.41399101],
    [0.74644090, 0.20020391, 0.03077999],
    [0.05948985, 0.10659048, 0.39884205],
    [0.56735781, 0.08485298, 0.11940265],
    [0.11178198, 0.04285385, 0.14161263],
    [0.34254479, 0.50627811, 0.05571580],
    [0.79268226, 0.35803827, 0.02544159],
    [0.01865226, 0.05139666, 0.28876921],
    [0.05440562, 0.29876767, 0.07183236],
    [0.45631278, 0.03075616, 0.04089930],
    [0.85385852, 0.56503529, 0.01470045],
    [0.53537579, 0.09006281, 0.30467248],
    [-0.03661893, 0.24753827, 0.39810356],
    [0.91186287, 0.91497635, 0.89391370],
Exemplo n.º 36
0
# -*- coding: utf-8 -*-
"""
Showcases colour quality plotting examples.
"""

import colour
from colour.plotting import (colour_style,
                             plot_multi_sds_colour_quality_scales_bars,
                             plot_multi_sds_colour_rendering_indexes_bars,
                             plot_single_sd_colour_quality_scale_bars,
                             plot_single_sd_colour_rendering_index_bars)
from colour.utilities import message_box

message_box('Colour Quality Plots')

colour_style()

message_box('Plotting "F2" illuminant "Colour Rendering Index (CRI)".')
plot_single_sd_colour_rendering_index_bars(colour.ILLUMINANTS_SDS['FL2'])

print('\n')

message_box(('Plotting various illuminants and light sources '
             '"Colour Rendering Index (CRI)".'))
plot_multi_sds_colour_rendering_indexes_bars(
    (colour.ILLUMINANTS_SDS['FL2'],
     colour.LIGHT_SOURCES_SDS['F32T8/TL841 (Triphosphor)'],
     colour.LIGHT_SOURCES_SDS['Kinoton 75P']))

print('\n')
Exemplo n.º 37
0
# -*- coding: utf-8 -*-
"""
Showcases *Colour - Datasets* loading.
"""

from colour.utilities import message_box

import colour_datasets

message_box('Listing the available datasets.\n\n'
            'Note: A ticked checkbox means that the particular dataset '
            'has been synced locally.')
print(colour_datasets.datasets())

message_box('A dataset is loaded by using its unique number: "3245895"')
print(colour_datasets.load('3245895'))

message_box('Or alternatively its full title: "New Color Specifications '
            'for ColorChecker SG and Classic Charts - X-Rite (2016)"')
print(
    colour_datasets.load(
        'New Color Specifications for ColorChecker SG and Classic Charts - '
        'X-Rite (2016)'))
Exemplo n.º 38
0
# -*- coding: utf-8 -*-
"""
Showcases colour spectral bandpass dependence correction computations.
"""

import numpy as np

import colour
from colour.utilities import message_box

message_box('Spectral Bandpass Dependence Correction')

message_box(('Applying spectral bandpass dependence correction on a sample '
             'spectral distribution using "Stearns and Stearns (1988)" '
             'method:\n'
             '\n\t("Measured Values", "Corrected Values")'))
sample_sd_data = {
    380: 0.048,
    385: 0.051,
    390: 0.055,
    395: 0.060,
    400: 0.065,
    405: 0.068,
    410: 0.068,
    415: 0.067,
    420: 0.064,
    425: 0.062,
    430: 0.059,
    435: 0.057,
    440: 0.055,
    445: 0.054,
Exemplo n.º 39
0
# -*- coding: utf-8 -*-
"""
Showcases colour notation systems plotting examples.
"""

from colour.plotting import (colour_style, plot_multi_munsell_value_functions,
                             plot_single_munsell_value_function)
from colour.utilities import message_box

message_box('Colour Notation Systems Plots')

colour_style()

message_box('Plotting a single "Munsell" value function.')
plot_single_munsell_value_function('Ladd 1955')

print('\n')

message_box('Plotting multiple "Munsell" value functions.')
plot_multi_munsell_value_functions(['Ladd 1955', 'Saunderson 1944'])
Exemplo n.º 40
0
# -*- coding: utf-8 -*-
"""
Showcases *ICTCP* *colour encoding* computations.
"""

import numpy as np

import colour
from colour.utilities import message_box

message_box('"ICTCP" Colour Encoding Computations')

RGB = np.array([0.45620519, 0.03081071, 0.04091952])
message_box(('Converting from "ITU-R BT.2020" colourspace to "ICTCP" colour '
             'encoding given "RGB" values:\n'
             '\n\t{0}'.format(RGB)))
print(colour.RGB_to_ICTCP(RGB))

print('\n')

ICTCP = np.array([0.07351364, 0.00475253, 0.09351596])
message_box(('Converting from "ICTCP" colour encoding to "ITU-R BT.2020" '
             'colourspace given "ICTCP" values:\n'
             '\n\t{0}'.format(ICTCP)))
print(colour.ICTCP_to_RGB(ICTCP))
Exemplo n.º 41
0
# -*- coding: utf-8 -*-
"""
Showcases *Automatic Colour Conversion Graph* computations.
"""

import numpy as np

import colour
from colour.utilities import message_box

message_box('Automatic Colour Conversion Graph')

message_box('Converting a "ColorChecker" "dark skin" sample spectral '
            'distribution to "Output-Referred" "sRGB" colourspace.')

sd = colour.COLOURCHECKERS_SDS['ColorChecker N Ohta']['dark skin']
print(colour.convert(sd, 'Spectral Distribution', 'sRGB'))
print(
    colour.XYZ_to_sRGB(
        colour.sd_to_XYZ(sd, illuminant=colour.ILLUMINANTS_SDS['D65']) / 100))

print('\n')

RGB = np.array([0.45675795, 0.30986982, 0.24861924])
message_box(('Converting to "CAM16-UCS" colourspace from given '
             '"Output-Referred" "sRGB" colourspace values:\n'
             '\n\t{0}'.format(RGB)))
print(colour.convert(RGB, 'Output-Referred RGB', 'CAM16UCS'))
specification = colour.XYZ_to_CAM16(
    colour.sRGB_to_XYZ(RGB) * 100,
    XYZ_w=colour.xy_to_XYZ(
Exemplo n.º 42
0
# -*- coding: utf-8 -*-
"""
Showcases contrast sensitivity computations.
"""

from pprint import pprint

import numpy as np
from scipy.optimize import fmin

import colour
from colour.utilities import as_float, message_box
from colour.plotting import colour_style, plot_single_function

message_box('Contrast Sensitivity Computations')

colour_style()

message_box(('Computing the contrast sensitivity for a spatial frequency "u" '
             'of 4, an angular size "X_0" of 60 and a retinal illuminance "E" '
             'of 65 using "Barten (1999)" method.'))
pprint(colour.contrast_sensitivity_function(u=4, X_0=60, E=65))
pprint(
    colour.contrast.contrast_sensitivity_function_Barten1999(
        u=4, X_0=60, E=65))

print('\n')

message_box(('Computing the minimum detectable contrast with the assumed '
             'conditions for UHDTV applications as given in "ITU-R BT.2246-4"'
             '"Figure 31" and using "Barten (1999)" method.'))
Exemplo n.º 43
0
import colour
from colour.plotting import (
    plot_RGB_colourspaces_in_chromaticity_diagram_CIE1931,
    plot_RGB_colourspaces_in_chromaticity_diagram_CIE1960UCS,
    plot_RGB_colourspaces_in_chromaticity_diagram_CIE1976UCS,
    plot_RGB_chromaticities_in_chromaticity_diagram_CIE1931,
    plot_RGB_chromaticities_in_chromaticity_diagram_CIE1960UCS,
    plot_RGB_chromaticities_in_chromaticity_diagram_CIE1976UCS,
    colour_style,
    plot_multi_cctfs,
    plot_single_cctf,
)
from colour.utilities import message_box

message_box("Colour Models Plots")

colour_style()

message_box('Plotting "RGB" colourspaces in the '
            '"CIE 1931 Chromaticity Diagram".')
pprint(sorted(colour.RGB_COLOURSPACES.keys()))
plot_RGB_colourspaces_in_chromaticity_diagram_CIE1931(
    ["ITU-R BT.709", "ACEScg", "S-Gamut"], show_pointer_gamut=True)

print("\n")

message_box('Plotting "RGB" colourspaces in the '
            '"CIE 1960 UCS Chromaticity Diagram".')
pprint(sorted(colour.RGB_COLOURSPACES.keys()))
plot_RGB_colourspaces_in_chromaticity_diagram_CIE1960UCS(
Exemplo n.º 44
0
"""Showcases *Y'CbCr* *colour encoding* computations."""

import numpy as np

import colour
from colour.utilities import message_box

message_box('"Y\'CbCr" Colour Encoding Computations')

RGB = np.array([0.45620519, 0.03081071, 0.04091952])
message_box(
    f'Converting to the "Y\'CbCr" colour encoding from given "ITU-R BT.709" '
    f"colourspace values:\n\n\t{RGB}")
print(colour.RGB_to_YCbCr(RGB))

print("\n")

message_box(
    f'Converting to the "Y\'CbCr" colour encoding from given"ITU-R BT.601" '
    f"colourspace values using legal range and integer output:\n\n\t{RGB}")
print(
    colour.RGB_to_YCbCr(RGB,
                        colour.WEIGHTS_YCBCR["ITU-R BT.601"],
                        out_legal=True,
                        out_int=True))

print("\n")

YCbCr = np.array([101, 111, 124])
message_box(
    f'Converting to the "ITU-R BT.601" colourspace from given "Y\'CbCr" '
Exemplo n.º 45
0
# -*- coding: utf-8 -*-
"""
Showcases colour matching functions computations.
"""

from pprint import pprint

import colour
from colour.utilities import message_box

message_box('Colour Matching Functions Computations')

message_box('Colour matching functions dataset.')
pprint(sorted(colour.CMFS.keys()))

print('\n')

message_box(('Converting from "Wright & Guild 1931 2 Degree RGB CMFs" colour '
             'matching functions to "CIE 1931 2 Degree Standard Observer" at '
             'wavelength 700 nm.'))
print(
    colour.STANDARD_OBSERVERS_CMFS['CIE 1931 2 Degree Standard Observer'][700])
print(colour.colorimetry.RGB_2_degree_cmfs_to_XYZ_2_degree_cmfs(700))

print('\n')

message_box(('Converting from "Stiles & Burch 1959 10 Degree RGB CMFs" colour '
             'matching functions to "CIE 1964 10 Degree Standard Observer" at '
             'wavelength 700 nm.'))
print(colour.STANDARD_OBSERVERS_CMFS['CIE 1964 10 Degree Standard Observer'][
    700])
Exemplo n.º 46
0
# -*- coding: utf-8 -*-
"""
Showcases *Colour Fidelity Index* (CFI) computations.
"""

from pprint import pprint

import colour
from colour.utilities import message_box

message_box('Colour Fidelity Index Computations')

message_box('Computing "F2" illuminant "Colour Fidelity Index (CFI)".')
print(colour.colour_fidelity_index(colour.SDS_ILLUMINANTS['FL2']))
print(
    colour.colour_fidelity_index(
        colour.SDS_ILLUMINANTS['FL2'], method='CIE 2017'))
print(
    colour.quality.colour_fidelity_index_CIE2017(
        colour.SDS_ILLUMINANTS['FL2']))
print(
    colour.colour_fidelity_index(
        colour.SDS_ILLUMINANTS['FL2'], method='ANSI/IES TM-30-18'))
print(
    colour.quality.colour_fidelity_index_ANSIIESTM3018(
        colour.SDS_ILLUMINANTS['FL2']))

print('\n')

message_box(('Computing "F2" illuminant "Colour Fidelity Index" (CFI) with '
             'detailed output data.'))
Exemplo n.º 47
0
# -*- coding: utf-8 -*-
"""
Showcases *Academy Color Encoding System* *Input Device Transform* related
computations.
"""

import colour
from colour.utilities import message_box

message_box('"ACES" "Input Device Transform" Computations')

message_box(('Computing "ACES" relative exposure '
             'values for some colour rendition chart spectral '
             'distributions:\n'
             '\n\t("dark skin", \n\t"blue sky")'))
print(
    colour.sd_to_aces_relative_exposure_values(
        colour.COLOURCHECKERS_SDS['ColorChecker N Ohta']['dark skin']))
print(
    colour.sd_to_aces_relative_exposure_values(
        colour.COLOURCHECKERS_SDS['ColorChecker N Ohta']['blue sky']))

print('\n')

message_box(('Computing "ACES" relative exposure values for various ideal '
             'reflectors:\n'
             '\n\t("18%", \n\t"100%")'))
wavelengths = colour.models.ACES_RICD.wavelengths
gray_reflector = colour.SpectralDistribution(
    dict(zip(wavelengths, [0.18] * len(wavelengths))), name='18%')
print(repr(colour.sd_to_aces_relative_exposure_values(gray_reflector)))
Exemplo n.º 48
0
"""
Showcases reflectance recovery computations using *Mallett et al. (2019)*
method.
"""

import numpy as np

import colour
from colour.utilities import message_box

message_box('"Mallett et al. (2019)" - Reflectance Recovery Computations')

illuminant = colour.SDS_ILLUMINANTS["D65"]

XYZ = np.array([0.20654008, 0.12197225, 0.05136952])
RGB = colour.XYZ_to_sRGB(XYZ, apply_cctf_encoding=False)
message_box(
    f'Recovering reflectance using "Mallett et al. (2019)" method from given '
    f'"XYZ" tristimulus values:\n\n\tXYZ: {XYZ}')
sd = colour.XYZ_to_sd(XYZ, method="Mallett 2019")
print(sd)
print(colour.recovery.RGB_to_sd_Mallett2019(RGB))
print(colour.sd_to_XYZ(sd, illuminant=illuminant) / 100)

print("\n")

message_box('Generating the "Mallett et al. (2019)" basis functions for the '
            "*Pal/Secam* colourspace:")
cmfs = (colour.MSDS_CMFS["CIE 1931 2 Degree Standard Observer"].copy().align(
    colour.SpectralShape(360, 780, 10)))
illuminant = colour.SDS_ILLUMINANTS["D65"].copy().align(cmfs.shape)
Exemplo n.º 49
0
# -*- coding: utf-8 -*-
"""
Showcases *Fairchild (1990)* chromatic adaptation model computations.
"""

import numpy as np

import colour
from colour.utilities import message_box

message_box('"Fairchild (1990)" Chromatic Adaptation Model Computations')

XYZ_1 = np.array([0.1953, 0.2307, 0.2497])
XYZ_n = np.array([1.1115, 1.0000, 0.3520])
XYZ_r = np.array([0.9481, 1.0000, 1.0730])
Y_n = 200
message_box(('Computing chromatic adaptation using "Fairchild (1990)" '
             'chromatic adaptation model.\n'
             '\n\t"XYZ_1":\n\t\t{0}\n\t"XYZ_n":\n\t\t{1}\n\t"XYZ_r":\n\t\t{2}'
             '\n\t"Y_n":\n\t\t{3}\n\n'
             'Warning: The input domain and output range of that definition '
             'are non standard!'.format(XYZ_1, XYZ_n, XYZ_r, Y_n)))
print(
    colour.chromatic_adaptation(
        XYZ_1, XYZ_n, XYZ_r, method='Fairchild 1990', Y_n=Y_n))
print(
    colour.adaptation.chromatic_adaptation_Fairchild1990(
        XYZ_1 * 100.0, XYZ_n, XYZ_r, Y_n) / 100.0)
Exemplo n.º 50
0
# -*- coding: utf-8 -*-
"""
Showcases colour models computations.
"""

import numpy as np

import colour
from colour.utilities import message_box

message_box('Colour Models Computations')

XYZ = np.array([0.20654008, 0.12197225, 0.05136952])
message_box(('Converting to "CIE xyY" colourspace from given "CIE XYZ" '
             'tristimulus values:\n'
             '\n\t{0}'.format(XYZ)))
print(colour.XYZ_to_xyY(XYZ))

print('\n')

message_box(('The default illuminant if X == Y == Z == 0 is '
             '"CIE Standard Illuminant D Series D65".'))
print(colour.XYZ_to_xyY(np.array([0.00000000, 0.00000000, 0.00000000])))

print('\n')

message_box('Using an alternative illuminant.')
print(
    colour.XYZ_to_xyY(
        np.array([0.00000000, 0.00000000, 0.00000000]),
        colour.ILLUMINANTS['CIE 1931 2 Degree Standard Observer']['ACES'],
Exemplo n.º 51
0
# -*- coding: utf-8 -*-
"""
Showcases dominant wavelength and purity of a colour computations.
"""

import numpy as np

import colour
from colour.utilities import message_box

message_box('Dominant Wavelength and Purity')

xy = np.array([0.54369557, 0.32107944])
xy_n = np.array([0.31270, 0.32900])
cmfs = colour.CMFS['CIE 1931 2 Degree Standard Observer']
message_box(('Computing the "dominant wavelength" for colour stimulus "xy" '
             'and achromatic stimulus "xy_n" chromaticity coordinates:\n'
             '\n\txy   : {0}\n\txy_n : {1}'.format(xy, xy_n)))

print(colour.dominant_wavelength(xy, xy_n, cmfs))

print('\n')

xy = np.array([0.35000, 0.25000])
message_box(('Computing the "dominant wavelength" for colour stimulus "xy" '
             'and achromatic stimulus "xy_n" chromaticity coordinates:\n'
             '\n\txy   : {0}\n\txy_n : {1}\n\n'
             'In this case the "complementary dominant wavelength" indicated '
             'by a negative sign is returned because the first intersection is'
             ' located on the line of purples.'.format(xy, xy_n)))
    plot_blackbody_colours,
    plot_blackbody_spectral_radiance,
    colour_style,
    plot_multi_cmfs,
    plot_multi_illuminant_sds,
    plot_multi_lightness_functions,
    plot_multi_sds,
    plot_single_cmfs,
    plot_single_illuminant_sd,
    plot_single_lightness_function,
    plot_single_sd,
    plot_visible_spectrum,
)
from colour.utilities import message_box

message_box("Colorimetry Plots")

colour_style()

message_box("Plotting a single illuminant spectral " "distribution.")
plot_single_illuminant_sd("FL1")

print("\n")

message_box("Plotting multiple illuminants spectral distributions.")
pprint(sorted(colour.SDS_ILLUMINANTS.keys()))
plot_multi_illuminant_sds(
    ["A", "B", "C", "D50", "D55", "D60", "D65", "D75", "FL1"]
)

print("\n")
Exemplo n.º 53
0
# -*- coding: utf-8 -*-
"""
Showcases *Colour Quality Scale* (CQS) computations.
"""

from pprint import pprint

import colour
from colour.utilities import message_box

message_box('"Colour Quality Scale (CQS)" Computations')

message_box('Computing "F2" illuminant "Colour Quality Scale (CQS)".')
print(colour.colour_quality_scale(colour.ILLUMINANTS_SDS['FL2']))

print('\n')

message_box(('Computing "H38HT-100" mercury lamp "Colour Quality Scale (CQS)" '
             'with detailed output data.'))
pprint(
    colour.colour_quality_scale(
        colour.LIGHT_SOURCES_SDS['H38HT-100 (Mercury)'], additional_data=True))

print('\n')

message_box('Computing "SDW-T 100W/LV Super HPS" lamp '
            '"Colour Quality Scale (CQS)".')
print(
    colour.colour_quality_scale(
        colour.LIGHT_SOURCES_SDS['SDW-T 100W/LV (Super HPS)']))
Exemplo n.º 54
0
"""Showcases colour matching functions computations."""

from pprint import pprint

import colour
from colour.utilities import message_box

message_box("Colour Matching Functions Computations")

message_box("Colour matching functions dataset.")
pprint(sorted(colour.MSDS_CMFS.keys()))

print("\n")

message_box(
    'Converting from the "Wright & Guild 1931 2 Degree RGB CMFs" colour '
    'matching functions to the "CIE 1931 2 Degree Standard Observer" at '
    "wavelength 700 nm.")
print(colour.MSDS_CMFS["CIE 1931 2 Degree Standard Observer"][700])
print(colour.colorimetry.
      MSDS_CMFS_STANDARD_OBSERVER["CIE 1931 2 Degree Standard Observer"][700])
print(colour.colorimetry.RGB_2_degree_cmfs_to_XYZ_2_degree_cmfs(700))

print("\n")

message_box(
    'Converting from the "Stiles & Burch 1959 10 Degree RGB CMFs" colour '
    'matching functions to the "CIE 1964 10 Degree Standard Observer" at '
    "wavelength 700 nm.")
print(colour.MSDS_CMFS["CIE 1964 10 Degree Standard Observer"][700])
print(colour.colorimetry.
Exemplo n.º 55
0
# -*- coding: utf-8 -*-
"""
Showcases blackbody / planckian radiator computations.
"""

import colour
from colour.utilities import message_box

message_box('Blackbody / Planckian Radiator Computations')

message_box(('Computing the spectral distribution of a blackbody at '
             'temperature 5500 kelvin degrees and converting to "CIE XYZ" '
             'tristimulus values.'))
cmfs = colour.STANDARD_OBSERVERS_CMFS['CIE 1931 2 Degree Standard Observer']
blackbody_sd = colour.sd_blackbody(5500, cmfs.shape)
print(blackbody_sd)
XYZ = colour.sd_to_XYZ(blackbody_sd, cmfs)
print(XYZ)

print('\n')

message_box(('Computing the spectral radiance of a blackbody at wavelength '
             '500 nm and temperature 5500 kelvin degrees.'))
print(colour.colorimetry.blackbody_spectral_radiance(500 * 1e-9, 5500))
print(colour.colorimetry.planck_law(500 * 1e-9, 5500))
Exemplo n.º 56
0
# -*- coding: utf-8 -*-
"""
Showcases dominant wavelength and purity of a colour computations.
"""

import numpy as np

import colour
from colour.utilities import message_box

message_box('Dominant Wavelength and Purity')

xy = np.array([0.54369557, 0.32107944])
xy_n = np.array([0.31270, 0.32900])
cmfs = colour.MSDS_CMFS['CIE 1931 2 Degree Standard Observer']
message_box(('Computing the "dominant wavelength" for colour stimulus "xy" '
             'and achromatic stimulus "xy_n" chromaticity coordinates:\n'
             '\n\txy   : {0}\n\txy_n : {1}'.format(xy, xy_n)))

print(colour.dominant_wavelength(xy, xy_n, cmfs))

print('\n')

xy = np.array([0.35000, 0.25000])
message_box(('Computing the "dominant wavelength" for colour stimulus "xy" '
             'and achromatic stimulus "xy_n" chromaticity coordinates:\n'
             '\n\txy   : {0}\n\txy_n : {1}\n\n'
             'In this case the "complementary dominant wavelength" indicated '
             'by a negative sign is returned because the first intersection is'
             ' located on the line of purples.'.format(xy, xy_n)))
Exemplo n.º 57
0
# -*- coding: utf-8 -*-
"""
Showcases *RGB* colourspace derivation.
"""

import numpy as np

import colour
from colour.utilities import message_box

message_box('"RGB" Colourspace Derivation')

primaries = np.array([
    [0.73470, 0.26530],
    [0.00000, 1.00000],
    [0.00010, -0.07700],
])
whitepoint = np.array([0.32168, 0.33767])
message_box(('Computing the normalised primary matrix for "ACES2065-1" '
             'colourspace transforming from "ACES2065-1" colourspace to '
             '"CIE XYZ" tristimulus values using user defined primaries '
             'matrix and whitepoint:\n'
             '\n\t{0}\n\t{1}\n\t{2}\n\n\t{3}'.format(
                 primaries[0], primaries[1], primaries[2], whitepoint)))
print(colour.normalised_primary_matrix(primaries, whitepoint))

print('\n')

message_box(('Computing the normalised primary matrix for "ACES2065-1" '
             'colourspace transforming from "ACES2065-1" colourspace to '
             '"CIE XYZ" tristimulus values using colour models dataset.'))
Exemplo n.º 58
0
# -*- coding: utf-8 -*-
"""
Showcases *CIE XYZ* tristimulus values computations.
"""

import numpy as np

import colour
from colour.utilities import message_box

message_box('"CIE XYZ" Tristimulus Values Computations')

data_sample = {
    380: 0.048,
    385: 0.051,
    390: 0.055,
    395: 0.060,
    400: 0.065,
    405: 0.068,
    410: 0.068,
    415: 0.067,
    420: 0.064,
    425: 0.062,
    430: 0.059,
    435: 0.057,
    440: 0.055,
    445: 0.054,
    450: 0.053,
    455: 0.053,
    460: 0.052,
    465: 0.052,
Exemplo n.º 59
0
# -*- coding: utf-8 -*-
"""
Showcases *CIE 1994* chromatic adaptation model computations.
"""

import numpy as np

import colour
from colour.utilities import message_box

message_box('"CIE 1994" Chromatic Adaptation Model Computations')

XYZ_1 = np.array([0.2800, 0.2126, 0.0527])
xy_o1 = np.array([0.4476, 0.4074])
xy_o2 = np.array([0.3127, 0.3290])
Y_o = 20
E_o1 = 1000
E_o2 = 1000
message_box(('Computing chromatic adaptation using "CIE 1994" chromatic '
             'adaptation model.\n'
             '\n\t"XYZ_1":\n\t\t{0}\n\t"xy_o1":\n\t\t{1}\n\t"xy_o2":\n\t\t{2}'
             '\n\t"Y_o":\n\t\t{3}\n\t"E_o1":\n\t\t{4}'
             '\n\t"E_o2":\n\t\t{5}\n\n'
             'Warning: The input domain and output range of that definition '
             'are non standard!'.format(XYZ_1, xy_o1, xy_o2, Y_o, E_o1, E_o2)))
print(
    colour.chromatic_adaptation(
        XYZ_1,
        colour.xy_to_XYZ(xy_o1),
        colour.xy_to_XYZ(xy_o2),
        method='CIE 1994',
Exemplo n.º 60
0
"""Showcases *YCoCg* *colour encoding* computations."""

import numpy as np

import colour
from colour.utilities import message_box

message_box('"YCoCg" Colour Encoding Computations')

RGB = np.array([0.45620519, 0.03081071, 0.04091952])
message_box(
    f'Converting to the "YCoCg" colour encoding from given "RGB" colourspace '
    f"values:\n\n\t{RGB}")
print(colour.RGB_to_YCoCg(RGB))

print("\n")

YCoCg = np.array([0.13968653, 0.20764283, -0.10887582])
message_box(
    f'Converting to the "RGB" colourspace values from "YCoCg" colour encoding '
    f"values:\n\n\t{YCoCg}")
print(colour.YCoCg_to_RGB(YCoCg))