Beispiel #1
0
def sRgbToHdr(source: tuple[int, int, int]) -> tuple[int, int, int]:
    """
    大致思路:先做gamma correction,然后转入XYZ。 在xyY内将Y的极值由sRGB亮度调为输出
    亮度,然后转回输出色域的RGB。
    args:
    colour -- (0-255, 0-255, 0-255)
    """
    if source == (0, 0, 0):
        return (0, 0, 0)

    args = parse_args()
    srgb_brightness = args.sub_brightness
    screen_brightness = args.output_brightness
    target_colourspace = RGB_COLOURSPACE_BT2020
    if args.colourspace == 'dcip3':
        target_colourspace = RGB_COLOURSPACE_DCI_P3

    normalized_source = np.array(source) / 255
    linear_source = colour.oetf_inverse(normalized_source, 'ITU-R BT.709')
    xyz = colour.RGB_to_XYZ(linear_source, RGB_COLOURSPACE_sRGB.whitepoint,
                            D65_ILLUMINANT,
                            RGB_COLOURSPACE_sRGB.matrix_RGB_to_XYZ)
    xyy = colour.XYZ_to_xyY(xyz)
    srgb_luma = xyy[2]
    xyy[2] = xyy[2] * srgb_brightness / screen_brightness
    xyz = colour.xyY_to_XYZ(xyy)
    output = colour.XYZ_to_RGB(xyz, D65_ILLUMINANT,
                               target_colourspace.whitepoint,
                               target_colourspace.matrix_XYZ_to_RGB)
    output = apply_oetf(output, srgb_luma)
    output = np.trunc(output * 255)
    return (int(output[0]), int(output[1]), int(output[2]))
Beispiel #2
0
def make_ebu_test_colour_patch():
    luv_file = "./doc/ebu_test_colour_value.csv"
    luv_data = np.loadtxt(luv_file,
                          delimiter=",",
                          skiprows=1,
                          usecols=(5, 6, 7))

    # convert from Yu'v' to Yuv
    luv_data[:, 2] = luv_data[:, 2] * 2 / 3

    # Yuv to XYZ
    xy = colour.UCS_uv_to_xy(luv_data[:, 1:])
    xyY = np.stack((xy[:, 0], xy[:, 1], (luv_data[:, 0] / 100.0))).T
    # print(xyY)
    large_xyz = colour.xyY_to_XYZ(xyY)
    # print(large_xyz)
    rgb_name = 'ITU-R BT.709'
    illuminant_XYZ = colour.RGB_COLOURSPACES[rgb_name].whitepoint
    illuminant_RGB = colour.RGB_COLOURSPACES[rgb_name].whitepoint
    chromatic_adaptation_transform = 'Bradford'
    xyz_to_rgb_mtx = colour.RGB_COLOURSPACES[rgb_name].XYZ_to_RGB_matrix
    rgb_val = colour.XYZ_to_RGB(large_xyz, illuminant_XYZ, illuminant_RGB,
                                xyz_to_rgb_mtx, chromatic_adaptation_transform)
    print(rgb_val)
    # rgb_val = np.uint16(np.round((rgb_val ** 1/2.35) * 0xFFFF))
    # print(rgb_val)
    # print(rgb_val ** (1/2.2))
    rgb_val = np.uint8(np.round((rgb_val**(1 / 2.35)) * 0xFF))
    plot_color_patch(rgb_val, v_num=3, h_num=5)
Beispiel #3
0
def get_limits_ref():
    """ Gets the limits tabulated inside colour-science, for reference """
    limits['ref']['XYZ'] = colour.xyY_to_XYZ(
        colour.volume.ILLUMINANTS_OPTIMAL_COLOUR_STIMULI['D65'])
    convert(limits['ref'])
    for space in limits['ref'].keys():
        triangulate(space, kind='ref')
Beispiel #4
0
def color_correct(image,
                  ref_color_checker,
                  plot=False,
                  method='Cheung 2004',
                  **kwargs):
    assert method in {'Finlayson 2015', 'Cheung 2004', 'Vandermonde'}

    # Find the color checker swatches
    swatches = detect_colour_checkers_segmentation(image)[0][::-1]

    # define D65 as the standard illuminant we will use
    D65 = colour.ILLUMINANTS['CIE 1931 2 Degree Standard Observer']['D65']

    # convert the reference color checker to RGB, by going through XYZ and using the D65 illuminant
    ref_color_checker_RGB = colour.XYZ_to_RGB(
        colour.xyY_to_XYZ(list(ref_color_checker.data.values())),
        ref_color_checker.illuminant, D65,
        colour.RGB_COLOURSPACES['sRGB'].XYZ_to_RGB_matrix)

    # plot the color checkers overlapped with the colors extracted from the image
    if plot:
        # convert the uncorrected swatches extracted from the image from RGB to xyY by going through XYZ
        swatches_xyY = colour.XYZ_to_xyY(
            colour.RGB_to_XYZ(
                swatches, D65, D65,
                colour.RGB_COLOURSPACES['sRGB'].RGB_to_XYZ_matrix))

        # use the RGB reference color checker to correct just the color checker swatches from the image
        swatches_corrected = colour.colour_correction(swatches,
                                                      swatches,
                                                      ref_color_checker_RGB,
                                                      method=method,
                                                      **kwargs)

        # convert these color corrected swatches from RGB to xyY by going through XYZ
        swatches_corrected_xyY = colour.XYZ_to_xyY(
            colour.RGB_to_XYZ(
                swatches_corrected, D65, D65,
                colour.RGB_COLOURSPACES['sRGB'].RGB_to_XYZ_matrix))

        image_colour_checker = colour.characterisation.ColourChecker(
            'Uncorrected Image',
            OrderedDict(zip(ref_color_checker.data.keys(), swatches_xyY)), D65)
        image_colour_checker_corrected = colour.characterisation.ColourChecker(
            'Corrected Image with {:}'.format(method),
            OrderedDict(
                zip(ref_color_checker.data.keys(), swatches_corrected_xyY)),
            D65)

        plot_multi_colour_checkers([ref_color_checker, image_colour_checker])

        plot_multi_colour_checkers(
            [ref_color_checker, image_colour_checker_corrected])

    return colour.colour_correction(image,
                                    swatches,
                                    ref_color_checker_RGB,
                                    method=method,
                                    **kwargs)
Beispiel #5
0
def cs_convert_K_to_RGB(colour_temperature):
    xy = colour.CCT_to_xy(colour_temperature)
    xyY = np.array([xy[0], xy[1], 1])
    XYZ = colour.xyY_to_XYZ(xyY)
    sRGB = colour.RGB_COLOURSPACES['sRGB']
    RGB = colour.XYZ_to_RGB(XYZ, sRGB.whitepoint, sRGB.whitepoint,
                            sRGB.XYZ_to_RGB_matrix)
    return RGB[0], RGB[1], RGB[2]
Beispiel #6
0
def xyY_to_rgb_with_illuminant_c(xyY):
    """
    C光源のXYZ値をD65光源のRGB値に変換する
    """
    large_xyz = xyY_to_XYZ(xyY)
    illuminant_XYZ = C_WHITE
    illuminant_RGB = D65_WHITE
    chromatic_adaptation_transform = 'CAT02'
    xyz_to_rgb_matrix = sRGB_COLOURSPACE.XYZ_to_RGB_matrix
    rgb = XYZ_to_RGB(large_xyz, illuminant_XYZ, illuminant_RGB,
                     xyz_to_rgb_matrix, chromatic_adaptation_transform)

    return rgb
def my_HVC2RGB(HVC):
    xyY = colour.munsell_colour_to_xyY(HVC)
    XYZ = colour.xyY_to_XYZ(xyY)
    # The last step will involve using the *Munsell Renotation System*
    # illuminant which is *CIE Illuminant C*:
    # http://nbviewer.ipython.org/github/colour-science/colour-ipython/blob/master/notebooks/colorimetry/illuminants.ipynb#CIE-Illuminant-C
    # It is necessary in order to ensure white stays white when
    # converting to *sRGB* colourspace and its different whitepoint
    # (*CIE Standard Illuminant D65*) by performing chromatic
    # adaptation between the two different illuminant.
    rgb = colour.XYZ_to_sRGB(XYZ, C)
    RGB = [np.uint8(round(255 * x)) for x in rgb]
    return RGB
Beispiel #8
0
def spectrum_to_rgb(
    wavelength,
    spectrum,
    # cmfs=None,
    illuminant='LED-B3',
    Y=None,
):
    """
    Calculate the rgb color given a wavelength and spectrum. Note spectrum should have spacing of 1, 5, 10 or 10 nm.

    Parameters
    ----------
    wavelength
    spectrum
    cmfs
    illuminant

    Returns
    -------

    """

    # if is_uniform(wavelength) and interval(wavelength)
    XYZ = spectrum_to_XYZ(
        wavelength=wavelength,
        spectrum=spectrum,
        # cmfs=cmfs,
        illuminant=illuminant)

    XYZ = XYZ / 100

    if Y is not None:
        xyY = XYZ_to_xyY(XYZ)
        xyY[2] = Y
        XYZ = xyY_to_XYZ(xyY)

    # Convert to rgb. Note the illuminant doesn't matter here except for points
    # where XYZ=0.
    rgb = XYZ_to_sRGB(XYZ)

    return rgb
Beispiel #9
0
def prepare_cc():
    print(colour.COLOURCHECKERS.data.keys())
    cc = []
    for i in range(0, 24):
        xyY = colour.COLOURCHECKERS.data['colorchecker 2005'][1].data[i].xyY
        print(colour.COLOURCHECKERS.data['colorchecker 2005'][1].data[i].name)
        print(xyY)
        XYZ = colour.xyY_to_XYZ(xyY)
        Lab = colour.XYZ_to_Lab(XYZ)
        print(
            colour.XYZ_to_sRGB(
                XYZ, colour.ILLUMINANTS['CIE 1931 2 Degree Standard Observer']
                ['D50'], 'Bradford') * 255)
        # print(colour.ILLUMINANTS['CIE 1931 2 Degree Standard Observer']['D50'])
        XYZD65 = cam2xyz.XYZD50_XYZD65(XYZ)
        cc.append(XYZD65)
        print(XYZD65, ' ', colour.XYZ_to_sRGB(XYZD65) * 255)
        # print(XYZ, ' ' ,XYZD65)
        # print(colour.RGB_COLOURSPACES['sRGB'].whitepoint, ' ', ill2)
        # print(colour.XYZ_to_sRGB(XYZD65) * 255)
        # print(colour.COLOURCHECKERS.data['cc2005'][1].data[i])
    return cc
Beispiel #10
0
def run_chromatic_adaptation_on_ref_XYZ():
    """
    Perform chromatic adaptation of the measured tristimulus values
    into D50. Film balanced at 5500K so we should be exposing the test chart with
    5500K light and also measure the test chart with same color temperature.

    Results are written to global df and scaled to max value of 100.

    Returns:
      XYZ values of testing media white.
    """
    # This is the standard value from ICC specification.
    D50_XYZ = np.array([0.9642, 1, 0.8249])

    unadapted_XYZ = np.array(df[['refX', 'refY', 'refZ']])
    if args.white_x and args.white_y:
        test_white_XYZ = np.array(
            colour.xyY_to_XYZ([args.white_x, args.white_y, 1]))
        adapted_XYZ = colour.adaptation.chromatic_adaptation(
            unadapted_XYZ,
            test_white_XYZ,
            D50_XYZ,
            method='Von Kries',
            transform='Bradford')
    else:
        test_white_XYZ = D50_XYZ
        adapted_XYZ = unadapted_XYZ

    if args.debug:
        print('Refernce unadapted XYZ values:')
        print(unadapted_XYZ)
        print('D50 adapted XYZ values using Bradford CAT:')
        print(adapted_XYZ)

    # colprof expects max value to be 100.0.
    norm_XYZ = adapted_XYZ.transpose() / adapted_XYZ.max().max() * 100
    df['norm_refX'], df['norm_refY'], df['norm_refZ'] = norm_XYZ
    return test_white_XYZ
    datum.split()[0] + ' ' + datum.split()[1] + '/' + datum.split()[2]
    for datum in data[1:]
]

xyY_list_fromtable = [[np.float(x) for x in datum.split()[3:]]
                      for datum in data[1:]]

# adjust for y=0's
for xyY in xyY_list_fromtable:
    if xyY[1] == 0:
        xyY[1] = 1e-50

# Thuis didn't work
#xyY_list = [colour.munsell_colour_to_xyY(HVC) for HVC in Munsell_list]

XYZ_list_fromtable = [colour.xyY_to_XYZ(xyY) for xyY in xyY_list_fromtable]

rgb_list_fromtable = [[
    np.uint8(round(255 * x)) for x in colour.XYZ_to_sRGB(XYZ, C)
] for XYZ in XYZ_list_fromtable]
L = len(rgb_list_fromtable)
Munsell_RGB_lookuptable = [[Munsell_list[i], rgb_list_fromtable[i]]
                           for i in range(L)]

with open('Munsell_RGB_lookuptable.data', 'wb') as MRlt:
    # store the data as binary data stream
    pickle.dump(Munsell_RGB_lookuptable, MRlt)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
xs, ys, zs = [], [], []
Beispiel #12
0
from timeit import Timer
from typing import Any, Mapping

import numpy as np
from colour import RGB_COLOURSPACES, xyY_to_XYZ
from colour.models import RGB_COLOURSPACE_sRGB
from numba import njit
from numpy.typing import NDArray

sRGB_to_XYZ_d65_mat = RGB_COLOURSPACES["sRGB"].matrix_RGB_to_XYZ
sRGB_ILL = D65_ILL = RGB_COLOURSPACE_sRGB.whitepoint

# CIE 1931, 2 degree observer
xyY_D50 = np.array([[0.3457, 0.3585, 1.00]])
XYZ_D50 = xyY_to_XYZ(xyY_D50)

# these should be more precise, but they are truncated at this point in
# the srgb standard
xyY_D65 = np.array([[0.3127, 0.3290, 1.00]])
XYZ_D65: NDArray[np.float64] = xyY_to_XYZ(xyY_D65)

xyY_E = np.array([[1 / 3, 1 / 3, 1.0]])

_LUV_DVEC: NDArray[np.float64] = np.asarray([[1.0, 15.0, 3.0]]).T
_LUV_49_VEC: NDArray[np.float64] = np.asarray([4.0, 9.0])


# noinspection PyPep8Naming
@njit
def cct_to_D_xyY_jit(T: float) -> NDArray[np.float64]:
Beispiel #13
0
"""

from __future__ import division, unicode_literals

import numpy as np

import colour
from colour.utilities.verbose import message_box

message_box('"Lightness" Computations')

xyY = (0.4316, 0.3777, 0.1008)
message_box(('Computing "Lightness" "CIE Lab" reference value for given '
             '"CIE xyY" colourspace values:\n'
             '\n\t{0}'.format(xyY)))
print(np.ravel(colour.XYZ_to_Lab(colour.xyY_to_XYZ(xyY)))[0])

print('\n')

Y = 10.08
message_box(('Computing "Lightness" using '
             'Glasser, Mckinney, Reilly and Schnelle (1958) method for '
             'given "luminance" value:\n'
             '\n\t{0}'.format(Y)))
print(colour.lightness_Glasser1958(Y))
print(colour.lightness(Y, method='Glasser 1958'))

print('\n')

message_box(('Computing "Lightness" using Wyszecki (1963) method for '
             'given "luminance" value:\n'
message_box('Colour rendition charts spectral power distributions dataset.')
pprint(colour.COLOURCHECKERS_SPDS.keys())

print('\n')

message_box(('"ColorChecker 2005" colour rendition chart chromaticity '
             'coordinates data:\n'
             '\n\t("Patch Number", "Patch Name", "x", "y", "Y")'))
name, data, illuminant = colour.COLOURCHECKERS['ColorChecker 2005']
for index, name, x, y, Y in data:
    print(index, name, x, y, Y)

print('\n')

message_box(('Converting "ColorChecker 2005" colour rendition chart "CIE xyY" '
             'colourspace values to "sRGB" colourspace "RGB" values:\n'
             '\n\t("Patch Name", ["R", "G", "B"])'))
for index, name, x, y, Y in data:
    RGB = colour.xyY_to_XYZ(
        colour.XYZ_to_RGB(
            np.array([[x], [y], [Y]]),
            illuminant,
            colour.ILLUMINANTS[
                'CIE 1931 2 Degree Standard Observer']['D65'],
            colour.sRGB_COLOURSPACE.to_RGB,
            'Bradford',
            colour.sRGB_COLOURSPACE.transfer_function))

    RGB = [int(round(x * 255)) if x >= 0 else 0 for x in np.ravel(RGB)]
    print('"{0}": {1}'.format(name, RGB))
            AppleP3_D50RGB_to_XYZ = numpy.asarray(variables["D50XYZ"])
            AppleP3_D65RGB_to_XYZ = numpy.matmul(
                numpy.linalg.inv(AppleCATD50toD65),
                AppleP3_D50RGB_to_XYZ
            )

            AppleWhite50XYZ = numpy.matmul(variables["D50XYZ"], [1., 1., 1.])

            print("AppleWhite50 xyY:\n" + str(colour.XYZ_to_xyY(
                AppleWhite50XYZ, [0.3127, 0.3290])) + ", XYZ: " +
                str(AppleWhite50XYZ))

            colour_AppleCATD50toD65 = (
                colour.adaptation.chromatic_adaptation_matrix_VonKries(
                    AppleWhite50XYZ,
                    colour.xyY_to_XYZ([0.3127, 0.3290, 1.]),
                    transform=u"Bradford"
                )
            )
            print("Apple D50 to D65 CAT:\n" + str(colour_AppleCATD50toD65))

            sRGB = colour.models.sRGB_COLOURSPACE
            sRGB.use_derived_RGB_to_XYZ_matrix = True
            sRGB.use_derived_XYZ_to_RGB_matrix = True

            print("sRGB derived:\n" + str(sRGB.RGB_to_XYZ_matrix))

            AppleWhiteTestD50toD65XYZ = numpy.matmul(
                colour_AppleCATD50toD65,
                AppleWhite50XYZ
                )
Beispiel #16
0
print(colour.XYZ_to_xyY([0, 0, 0]))

print('\n')

message_box('Using an alternative illuminant.')
print(colour.XYZ_to_xyY(
    [0, 0, 0],
    colour.ILLUMINANTS['CIE 1931 2 Degree Standard Observer']['D60']))

print('\n')

xyY = [0.4325, 0.3788, 1.]
message_box(('Converting to "CIE XYZ" colourspace from given "CIE xyY" '
             'colourspace values:\n'
             '\n\t{0}'.format(xyY)))
print(colour.xyY_to_XYZ(xyY))

print('\n')

message_box(('Converting to "xy" chromaticity coordinates from given '
             '"CIE XYZ" colourspace values:\n'
             '\n\t{0}'.format(XYZ)))
print(colour.XYZ_to_xy(XYZ))

print('\n')

xy = (0.43249999995420696, 0.378800000065942)
message_box(('Converting to "CIE XYZ" colourspace from given "xy" '
             'chromaticity coordinates:\n'
             '\n\t{0}'.format(xy)))
print(colour.xy_to_XYZ(xy))
pprint(sorted(colour.COLOURCHECKERS.keys()))

print('\n')

message_box('Colour rendition charts spectral power distributions dataset.')
pprint(colour.COLOURCHECKERS_SPDS.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.COLOURCHECKERS['ColorChecker 2005']
for index, name, xyY in data:
    print(index, name, xyY)

print('\n')

message_box(('Converting "ColorChecker 2005" colour rendition chart "CIE xyY" '
             'colourspace values to "sRGB" colourspace "RGB" values:\n'
             '\n\t("Patch Name", ["R", "G", "B"])'))
for index, name, xyY in data:
    RGB = colour.XYZ_to_RGB(
        colour.xyY_to_XYZ(xyY), illuminant,
        colour.ILLUMINANTS['CIE 1931 2 Degree Standard Observer']['D65'],
        colour.RGB_COLOURSPACES['sRGB'].XYZ_to_RGB_matrix, 'Bradford',
        colour.RGB_COLOURSPACES['sRGB'].encoding_cctf)

    RGB = [int(round(x * 255)) if x >= 0 else 0 for x in np.ravel(RGB)]
    print('"{0}": {1}'.format(name, RGB))
message_box('Colour rendition charts spectral power distributions dataset.')
pprint(colour.COLOURCHECKERS_SPDS.keys())

print('\n')

message_box(('"ColorChecker 2005" colour rendition chart chromaticity '
             'coordinates data:\n'
             '\n\t("Patch Number", "Patch Name", "x", "y", "Y")'))
name, data, illuminant = colour.COLOURCHECKERS['ColorChecker 2005']
for index, name, x, y, Y in data:
    print(index, name, x, y, Y)

print('\n')

message_box(('Converting "ColorChecker 2005" colour rendition chart "CIE xyY" '
             'colourspace values to "sRGB" colourspace "RGB" values:\n'
             '\n\t("Patch Name", ["R", "G", "B"])'))
for index, name, x, y, Y in data:
    RGB = colour.XYZ_to_RGB(
        colour.xyY_to_XYZ(np.array([x, y, Y])),
        illuminant,
        colour.ILLUMINANTS[
            'CIE 1931 2 Degree Standard Observer']['D65'],
        colour.sRGB_COLOURSPACE.XYZ_to_RGB_matrix,
        'Bradford',
        colour.sRGB_COLOURSPACE.transfer_function)

    RGB = [int(round(x * 255)) if x >= 0 else 0 for x in np.ravel(RGB)]
    print('"{0}": {1}'.format(name, RGB))
Beispiel #19
0
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(
    'Converting the "ColorChecker 2005" colour rendition chart "CIE xyY" '
    'colourspace values to "sRGB" colourspace "RGB" values:\n\n'
    '\t("Patch Name", ["R", "G", "B"])'
)
for name, xyY in data.items():
    RGB = colour.XYZ_to_RGB(
        colour.xyY_to_XYZ(xyY),
        illuminant,
        colour.CCS_ILLUMINANTS["CIE 1931 2 Degree Standard Observer"]["D65"],
        colour.RGB_COLOURSPACES["sRGB"].matrix_XYZ_to_RGB,
        "Bradford",
        colour.RGB_COLOURSPACES["sRGB"].cctf_encoding,
    )

    RGB = [int(round(x * 255)) if x >= 0 else 0 for x in np.ravel(RGB)]
    print(f'"{name}": {RGB}')
pprint(sorted(colour.COLOURCHECKERS.keys()))

print('\n')

message_box('Colour rendition charts spectral distributions dataset.')
pprint(colour.COLOURCHECKERS_SDS.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.COLOURCHECKERS['ColorChecker 2005']
for name, xyY in data.items():
    print(name, xyY)

print('\n')

message_box(('Converting "ColorChecker 2005" colour rendition chart "CIE xyY" '
             'colourspace values to "sRGB" colourspace "RGB" values:\n'
             '\n\t("Patch Name", ["R", "G", "B"])'))
for name, xyY in data.items():
    RGB = colour.XYZ_to_RGB(
        colour.xyY_to_XYZ(xyY), illuminant,
        colour.ILLUMINANTS['CIE 1931 2 Degree Standard Observer']['D65'],
        colour.RGB_COLOURSPACES['sRGB'].XYZ_to_RGB_matrix, 'Bradford',
        colour.RGB_COLOURSPACES['sRGB'].encoding_cctf)

    RGB = [int(round(x * 255)) if x >= 0 else 0 for x in np.ravel(RGB)]
    print('"{0}": {1}'.format(name, RGB))
Beispiel #21
0
"""
Showcases *Lightness* computations.
"""

import numpy as np

import colour
from colour.utilities.verbose import message_box

message_box('"Lightness" Computations')

xyY = (0.4316, 0.3777, 0.1008)
message_box(('Computing "Lightness" "CIE Lab" reference value for given '
             '"CIE xyY" colourspace values:\n'
             '\n\t{0}'.format(xyY)))
print(np.ravel(colour.XYZ_to_Lab(colour.xyY_to_XYZ(xyY)))[0])

print('\n')

Y = 10.08
message_box(('Computing "Lightness" using '
             '"Glasser, Mckinney, Reilly and Schnelle (1958)" method for '
             'given "luminance" value:\n'
             '\n\t{0}'.format(Y)))
print(colour.lightness_Glasser1958(Y))
print(colour.lightness(Y, method='Glasser 1958'))

print('\n')

message_box(('Computing "Lightness" using "Wyszecki (1963)" method for '
             'given "luminance" value:\n'
pprint(sorted(colour.COLOURCHECKERS.keys()))

print('\n')

message_box('Colour rendition charts spectral power distributions dataset.')
pprint(colour.COLOURCHECKERS_SPDS.keys())

print('\n')

message_box(('"ColorChecker 2005" colour rendition chart chromaticity '
             'coordinates data:\n'
             '\n\t("Patch Number", "Patch Name", "x", "y", "Y")'))
name, data, illuminant = colour.COLOURCHECKERS['ColorChecker 2005']
for index, name, x, y, Y in data:
    print(index, name, x, y, Y)

print('\n')

message_box(('Converting "ColorChecker 2005" colour rendition chart "CIE xyY" '
             'colourspace values to "sRGB" colourspace "RGB" values:\n'
             '\n\t("Patch Name", ["R", "G", "B"])'))
for index, name, x, y, Y in data:
    RGB = colour.XYZ_to_RGB(
        colour.xyY_to_XYZ(np.array([x, y, Y])), illuminant,
        colour.ILLUMINANTS['CIE 1931 2 Degree Standard Observer']['D65'],
        colour.sRGB_COLOURSPACE.XYZ_to_RGB_matrix, 'Bradford',
        colour.sRGB_COLOURSPACE.encoding_cctf)

    RGB = [int(round(x * 255)) if x >= 0 else 0 for x in np.ravel(RGB)]
    print('"{0}": {1}'.format(name, RGB))
print('\n')

message_box('Colour rendition charts spectral power distributions dataset.')
pprint(colour.COLOURCHECKERS_SPDS.keys())

print('\n')

message_box(('"ColorChecker 2005" colour rendition chart chromaticity '
             'coordinates data:\n'
             '\n\t("Patch Number", "Patch Name", "x", "y", "Y")'))
name, data, illuminant = colour.COLOURCHECKERS['ColorChecker 2005']
for index, name, x, y, Y in data:
    print(index, name, x, y, Y)

print('\n')

message_box(('Converting "ColorChecker 2005" colour rendition chart "CIE xyY" '
             'colourspace values to "sRGB" colourspace "RGB" values:\n'
             '\n\t("Patch Name", ["R", "G", "B"])'))
for index, name, x, y, Y in data:
    RGB = colour.xyY_to_XYZ(
        colour.XYZ_to_RGB(
            np.array([[x], [y], [Y]]), illuminant,
            colour.ILLUMINANTS['CIE 1931 2 Degree Standard Observer']['D65'],
            colour.sRGB_COLOURSPACE.to_RGB, 'Bradford',
            colour.sRGB_COLOURSPACE.transfer_function))

    RGB = [int(round(x * 255)) if x >= 0 else 0 for x in np.ravel(RGB)]
    print('"{0}": {1}'.format(name, RGB))
Beispiel #24
0
 def convert_xyYtoXYZ(data):
     xyz = colour.xyY_to_XYZ(data)
     return colour.adaptation.chromatic_adaptation_VonKries(
         xyz, XYZ_ws, XYZ_wt, transform='CAT02')
Beispiel #25
0
    def load(self):
        """
        Syncs, parses, converts and returns the *Hung and Berns (1995)*
        *Constant Hue Loci Data* dataset content.

        Returns
        -------
        OrderedDict
            *Hung and Berns (1995)* *Constant Hue Loci Data* dataset content.

        Examples
        --------
        >>> from colour_datasets.utilities import suppress_stdout
        >>> dataset = DatasetLoader_Hung1995()
        >>> with suppress_stdout():
        ...     dataset.load()
        >>> len(dataset.content.keys())
        6
        """

        super(DatasetLoader_Hung1995, self).sync()

        self._content = OrderedDict()

        filenames = OrderedDict([
            ('Table I.csv', 'Reference colors.'),
            ('Table II.csv', 'Intra- and interobserver variances for each '
             'reference hue expressed in circumferential '
             'hue-angle difference.'),
            ('Table III.csv', 'Weight-averaged constant hue loci for the CL '
             'experiment.'),
            ('Table IV.csv', 'Weight-averaged constant hue loci for the VL '
             'experiment.'),
        ])

        for filename in filenames:
            datafile_path = os.path.join(self.record.repository, 'dataset',
                                         filename)

            self._content[filename.split('.')[0]] = np.genfromtxt(
                datafile_path,
                delimiter=',',
                names=True,
                dtype=None,
                encoding='utf-8')

        hues = [
            'Red', 'Red-yellow', 'Yellow', 'Yellow-green', 'Green',
            'Green-cyan', 'Cyan', 'Cyan-blue', 'Blue', 'Blue-magenta',
            'Magenta', 'Magenta-red'
        ]

        XYZ_r = xy_to_XYZ(
            CCS_ILLUMINANTS['CIE 1931 2 Degree Standard Observer']['C'])

        for table, experiment in [('Table III', 'CL'), ('Table IV', 'VL')]:
            key = 'Constant Hue Loci Data - {0}'.format(experiment)
            self._content[key] = OrderedDict()
            for hue in hues:
                for sample_r in self._content['Table I']:
                    sample_r = sample_r.tolist()
                    if sample_r[0] == hue:
                        XYZ_cr = xyY_to_XYZ(sample_r[1:4]) / 100
                        break

                XYZ_ct = []
                metadata = {
                    'Color name': [],
                    'C*uv': [],
                }
                for sample_t in self._content[table]:
                    sample_t = sample_t.tolist()
                    if not sample_t[0] == hue:
                        continue

                    XYZ_ct.append(sample_t[2:])
                    metadata['Color name'].append(sample_t[0])
                    metadata['C*uv'].append(sample_t[1])

                self._content[key][hue] = (
                    ConstantPerceivedHueColourMatches_Hung1995(
                        hue, XYZ_r, XYZ_cr,
                        np.vstack(XYZ_ct) / 100, metadata))

        return self._content
Beispiel #26
0
    if args.g:
        g = read_txt_readings(args.g)
    else:
        g = build_empty(src, 'g')
    if args.b:
        b = read_txt_readings(args.b)
    else:
        b = build_empty(src, 'b')
    if args.Yxy:
        Yxy = read_txt_readings(args.Yxy)
    elif args.XYZ:
        XYZ = read_txt_readings(args.XYZ)

    if not args.Yxy and not args.XYZ:
        print('patch', 'r', 'g', 'b', 'refR', 'refG', 'refB')
        for patch, vals in src.items():
            print(patch, vals['r'], vals['g'], vals['b'], r[patch]['r'],
                  g[patch]['g'], b[patch]['b'])
    else:
        print('patch', 'r', 'g', 'b', 'refR', 'refG', 'refB', 'refX', 'refY',
              'refZ')

        for patch, vals in src.items():
            if args.Yxy:
                X, Y, Z = colour.xyY_to_XYZ(
                    [Yxy[patch]['x'], Yxy[patch]['y'], Yxy[patch]['Y']])
            elif args.XYZ:
                X, Y, Z = XYZ[patch]['X'], XYZ[patch]['Y'], XYZ[patch]['Z']
            print(patch, vals['r'], vals['g'], vals['b'], r[patch]['r'],
                  g[patch]['g'], b[patch]['b'], X, Y, Z)
            "scipy.interpolate",
            "scipy.linalg",
            "scipy.ndimage",
            "scipy.ndimage.filters",
            "scipy.spatial",
            "scipy.spatial.distance",
            "scipy.optimize",
    ):
        sys.modules[str(module)] = MockModule(str(module))


if __name__ == "__main__":
    import sys

    for module in (
            "scipy",
            "scipy.interpolate",
            "scipy.linalg",
            "scipy.ndimage",
            "scipy.ndimage.filters",
            "scipy.spatial",
            "scipy.spatial.distance",
            "scipy.optimize",
    ):
        sys.modules[str(module)] = MockModule(str(module))

    import colour

    xyY = (0.4316, 0.3777, 0.1008)
    print(colour.xyY_to_XYZ(xyY))
Beispiel #28
0
# - bevorzugt in der Druckindustrie.
# - Weißpunkt für Wide-Gamut-RGB und Color-Match-RGB
#
# D65:
# - entspricht etwa einem grau verhangenen Himmel
# - genutzt wird dieses Normlicht als Weißpunkt für sRGB, Adobe-RGB und die PAL/SECAM-TV-Norm

OBSERVER_2 = colour.ILLUMINANTS.get('CIE 1931 2 Degree Standard Observer')
# OBSERVER_10 = colour.ILLUMINANTS.get('CIE 1964 10 Degree Standard Observer')

ILLUMINANT_D50_2 = OBSERVER_2.get('D50')
# ILLUMINANT_D50_10 = OBSERVER_10.get('D50')
ILLUMINANT_D65_2 = OBSERVER_2.get('D65')
# ILLUMINANT_D65_10 = OBSERVER_10.get('D65')

WHITEPOINT_D50_2 = colour.xyY_to_XYZ([ILLUMINANT_D50_2[0], ILLUMINANT_D50_2[1], 1]) * 100
# WHITEPOINT_D50_10 = colour.xyY_to_XYZ([ILLUMINANT_D50_10[0], ILLUMINANT_D50_10[1], 1]) * 100
WHITEPOINT_D65_2 = colour.xyY_to_XYZ([ILLUMINANT_D65_2[0], ILLUMINANT_D65_2[1], 1]) * 100
# WHITEPOINT_D65_10 = colour.xyY_to_XYZ([ILLUMINANT_D65_10[0], ILLUMINANT_D65_10[1], 1]) * 100

# Typische Beleuchtungsstärken:
# - Heller Sonnentag       100.000 lx
# - Bedeckter Sommertag     20.000 lx
# - Im Schatten im Sommer   10.000 lx
# - Bedeckter Wintertag      3.500 lx
# - Elite-Fußballstadion     1.400 lx
# - Beleuchtung TV-Studio    1.000 lx
# - Büro-/Zimmerbeleuchtung    500 lx
# - Flurbeleuchtung            100 lx
# - Wohnzimmer[6]               50 lx
# - Straßenbeleuchtung          10 lx