File: density.py

package info (click to toggle)
python-colormath 3.0.0-1.1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 300 kB
  • sloc: python: 3,657; makefile: 3
file content (66 lines) | stat: -rw-r--r-- 2,494 bytes parent folder | download | duplicates (3)
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
"""
Formulas for density calculation.
"""

from math import log10
from colormath.density_standards import ANSI_STATUS_T_BLUE, ANSI_STATUS_T_GREEN, \
    ANSI_STATUS_T_RED, VISUAL_DENSITY_THRESH, ISO_VISUAL


def ansi_density(color, density_standard):
    """
    Calculates density for the given SpectralColor using the spectral weighting
    function provided. For example, ANSI_STATUS_T_RED. These may be found in
    :py:mod:`colormath.density_standards`.
    
    :param SpectralColor color: The SpectralColor object to calculate
        density for.
    :param numpy.ndarray std_array: NumPy array of filter of choice
        from :py:mod:`colormath.density_standards`.
    :rtype: float
    :returns: The density value for the given color and density standard.
    """
    # Load the spec_XXXnm attributes into a Numpy array.
    sample = color.get_numpy_array()
    # Matrix multiplication
    intermediate = sample * density_standard
    
    # Sum the products.
    numerator = intermediate.sum()
    # This is the denominator in the density equation.
    sum_of_standard_wavelengths = density_standard.sum()
    
    # This is the top level of the density formula.
    return -1.0 * log10(numerator / sum_of_standard_wavelengths)


def auto_density(color):
    """
    Given a SpectralColor, automatically choose the correct ANSI T filter.
    Returns a tuple with a string representation of the filter the
    calculated density.

    :param SpectralColor color: The SpectralColor object to calculate
        density for.
    :rtype: float
    :returns: The density value, with the filter selected automatically.
    """
    blue_density = ansi_density(color, ANSI_STATUS_T_BLUE)
    green_density = ansi_density(color, ANSI_STATUS_T_GREEN)
    red_density = ansi_density(color, ANSI_STATUS_T_RED)
    
    densities = [blue_density, green_density, red_density]
    min_density = min(densities)
    max_density = max(densities)
    density_range = max_density - min_density
    
    # See comments in density_standards.py for VISUAL_DENSITY_THRESH to
    # understand what this is doing.
    if density_range <= VISUAL_DENSITY_THRESH:
        return ansi_density(color, ISO_VISUAL)
    elif blue_density > green_density and blue_density > red_density:
        return blue_density
    elif green_density > blue_density and green_density > red_density:
        return green_density
    else:
        return red_density