Пример #1
0
def get_colorspace_matrix(colorspace, primaries_only=False, inv=False):
    """Return a colorspace RGB to XYZ matrix.

    Args:
        colorspace (str): input colorspace.

    Kwargs:
        primaries_only (bool): primaries matrix only, doesn't include white point.
        inv (bool): return XYZ to RGB matrix.

    Returns:
        .numpy.matrix (3x3)

    """
    from utils.colorspaces import COLORSPACES
    from utils.private_colorspaces import PRIVATE_COLORSPACES
    colorspace_obj = COLORSPACES.get(colorspace) or PRIVATE_COLORSPACES.get(
        colorspace)

    if not colorspace_obj:
        raise NotImplementedError(
            "Could not find {0} colorspace".format(colorspace))

    if primaries_only:
        matrix = get_primaries_matrix(colorspace_obj.get_red_primaries(),
                                      colorspace_obj.get_green_primaries(),
                                      colorspace_obj.get_blue_primaries())
    else:
        matrix = get_RGB_to_XYZ_matrix(colorspace_obj.get_red_primaries(),
                                       colorspace_obj.get_green_primaries(),
                                       colorspace_obj.get_blue_primaries(),
                                       colorspace_obj.get_white_point())
    if inv:
        return matrix.I
    return matrix
Пример #2
0
def get_colorspace_matrix(colorspace, primaries_only=False, inv=False):
    """Return a colorspace RGB to XYZ matrix.

    Args:
        colorspace (str): input colorspace.

    Kwargs:
        primaries_only (bool): primaries matrix only, doesn't include white point.
        inv (bool): return XYZ to RGB matrix.

    Returns:
        .numpy.matrix (3x3)

    """
    from utils.colorspaces import COLORSPACES
    from utils.private_colorspaces import PRIVATE_COLORSPACES
    colorspace_obj = COLORSPACES.get(colorspace) or PRIVATE_COLORSPACES.get(colorspace)

    if not colorspace_obj:
        raise NotImplementedError("Could not find {0} colorspace".format(colorspace))

    if primaries_only:
        matrix = get_primaries_matrix(colorspace_obj.get_red_primaries(),
                                      colorspace_obj.get_green_primaries(),
                                      colorspace_obj.get_blue_primaries())
    else:
        matrix = get_RGB_to_XYZ_matrix(colorspace_obj.get_red_primaries(),
                                       colorspace_obj.get_green_primaries(),
                                       colorspace_obj.get_blue_primaries(),
                                       colorspace_obj.get_white_point())
    if inv:
        return matrix.I
    return matrix
Пример #3
0
def __get_options():
    """Return plot that chroma option parser

    Returns:
        .argparse.ArgumentParser.args

    """
    # Define parser
    description = 'Plot chromaticities in a xy or u\'v\' diagram'
    parser = argparse.ArgumentParser(description=description)
    # RGB colorspace
    parser.add_argument("-space",
                        "--colorspace",
                        help=("RGB Colorspace."),
                        type=str,
                        action='append',
                        dest='colorspaces',
                        choices=sorted(
                            list(COLORSPACES.keys()) +
                            list(PRIVATE_COLORSPACES.keys())))
    # Points
    parser.add_argument("-p",
                        "--point",
                        type=float,
                        nargs=2,
                        metavar=('x', 'y'),
                        action='append',
                        dest='points',
                        help='Display an xy point')
    # Spectrum locus
    parser.add_argument("-spectrum",
                        "--spectrum-locus",
                        action="store_true",
                        help="Display spectrum locus")
    return parser
Пример #4
0
def __get_options():
    """ Return rgb_to_xyz option parser

    Returns:
        .argparse.ArgumentParser.args

    """
    # Define parser
    description = 'Print RGB -> RGB matrix'
    parser = argparse.ArgumentParser(description=description)
    # RGB colorspace
    colorspaces = sorted(
        list(COLORSPACES.keys()) + list(PRIVATE_COLORSPACES.keys()) +
        [XYZ_colorspace])
    parser.add_argument("-in",
                        "--in-colorspace",
                        help=("Input RGB Colorspace."),
                        type=str,
                        choices=colorspaces,
                        required=True)
    parser.add_argument("-out",
                        "--out-colorspace",
                        help=("Output RGB Colorspace."),
                        type=str,
                        choices=colorspaces,
                        required=True)
    # Get primarie matrix only
    parser.add_argument(
        "-po",
        "--primaries-only",
        help="Primaries matrix only, doesn't include white point.",
        action="store_true")
    # Output format
    parser.add_argument("-f",
                        "--format",
                        help=("Output formatting."),
                        type=str,
                        choices=['matrix', 'spimtx', 'simple'],
                        default='matrix')
    # version
    parser.add_argument('-v',
                        "--version",
                        action='version',
                        version='{0} - version {1}'.format(
                            description, __version__))
    # full version
    versions = debug_helper.get_imported_modules_versions(
        sys.modules, globals())
    versions = '{0} - version {1}\n\n{2}'.format(description, __version__,
                                                 versions)
    parser.add_argument('-V',
                        "--full-versions",
                        action=debug_helper.make_full_version_action(versions))
    return parser.parse_args()
Пример #5
0
def __get_options():
    """Return curve_to_lut option parser

    Returns:
        .argparse.ArgumentParser.args

    """
    ## Define parser
    description = 'Create lut file corresponding to a colorspace gradation'
    parser = argparse.ArgumentParser(description=description)
    # RGB colorspace
    parser.add_argument("colorspace",
                        help=("Input RGB Colorspace."),
                        type=str,
                        choices=sorted(COLORSPACES.keys() +
                                        PRIVATE_COLORSPACES.keys()))
    # output lut
    parser.add_argument("outlutpath", help=("path to the output LUT."
                                                      " Can be a file or a "
                                                      "directory."
                                                      ), type=str)
    # type
    parser.add_argument("-t", "--out-type", help=("Output LUT type."),
                        type=str, choices=['1D_CSP', '1D_CUBE', '1D_SPI'],
                        default='1D_CUBE')
    # in range
    parser.add_argument("-ir", "--in-range", help=("In range value."),
                        type=float, default=0.0)
    # out range
    parser.add_argument("-or", "--out-range", help=("Out range value."),
                        type=float, default=1.0)
    # out lut size
    parser.add_argument("-os", "--out-lut-size", help=(
        "Output lut bit precision. Ex : 10, 16, 32."
    ), default=16, type=int)
    # direction
    parser.add_argument("-d", "--direction", help=("Direction : "
                                                   "encode or decode."),
                        type=str, choices=[Direction.ENCODE, Direction.DECODE],
                        default=Direction.ENCODE)
    # version
    parser.add_argument('-v', "--version", action='version',
                        version='{0} - version {1}'.format(description,
                                                           __version__))
    # full version
    versions = debug_helper.get_imported_modules_versions(sys.modules,
                                                          globals())
    versions = '{0} - version {1}\n\n{2}'.format(description,
                                                 __version__,
                                                 versions)
    parser.add_argument('-V', "--full-versions",
                        action=debug_helper.make_full_version_action(versions))
    return parser.parse_args()
Пример #6
0
def __get_options():
    """ Return rgb_to_xyz option parser

    Returns:
        .argparse.ArgumentParser.args

    """
    # Define parser
    description = 'Print RGB -> RGB matrix'
    parser = argparse.ArgumentParser(description=description)
    # RGB colorspace
    colorspaces = sorted(COLORSPACES.keys() + PRIVATE_COLORSPACES.keys() + [XYZ_colorspace])
    parser.add_argument("-in", "--in-colorspace",
                        help=("Input RGB Colorspace."),
                        type=str,
                        choices=colorspaces,
                        required=True)
    parser.add_argument("-out", "--out-colorspace",
                        help=("Output RGB Colorspace."),
                        type=str,
                        choices=colorspaces,
                        required=True)
    # Get primarie matrix only
    parser.add_argument("-po", "--primaries-only",
                        help="Primaries matrix only, doesn't include white point.",
                        action="store_true")
    # Output format
    parser.add_argument("-f", "--format",
                        help=("Output formatting."),
                        type=str,
                        choices=['matrix', 'spimtx', 'simple'],
                        default='matrix')
    # version
    parser.add_argument('-v', "--version", action='version',
                        version='{0} - version {1}'.format(description,
                                                           __version__))
    # full version
    versions = debug_helper.get_imported_modules_versions(sys.modules,
                                                          globals())
    versions = '{0} - version {1}\n\n{2}'.format(description,
                                                 __version__,
                                                 versions)
    parser.add_argument('-V', "--full-versions",
                        action=debug_helper.make_full_version_action(versions))
    return parser.parse_args()
Пример #7
0
def __get_options():
    """Return curve_to_lut option parser

    Returns:
        .argparse.ArgumentParser.args

    """
    # Define parser
    description = ('Create lut file corresponding to a colorspace or gamma '
                   'gradation')
    parser = argparse.ArgumentParser(description=description)
    # RGB colorspace
    action = parser.add_mutually_exclusive_group(required=True)
    action.add_argument("--colorspace",
                        help=("Input RGB Colorspace."),
                        type=str,
                        choices=sorted(list(COLORSPACES.keys()) +
                                       list(PRIVATE_COLORSPACES.keys())))
    action.add_argument("--gamma",
                        help="Input pure gamma gradation",
                        type=float)
    # direction
    parser.add_argument("-d", "--direction", help=("Direction : "
                                                   "encode or decode."),
                        type=str, choices=[Direction.ENCODE, Direction.DECODE],
                        default=Direction.ENCODE)
    # out lut file, type, format, ranges,  out bit depth, out cube size
    add_outlutfile_option(parser, required=True)
    add_export_lut_options(parser)
    parser.add_argument("--process-input-range", action="store_true",
                        help=("If true, input range will be computed from "
                              " colorspace gradation functions."
                              "(Colorspace only))"))
    # version
    full_version = debug_helper.get_imported_modules_versions(sys.modules,
                                                              globals())
    add_version_option(parser, description, __version__, full_version)
    # verbose
    add_silent_option(parser)
    # trace
    add_trace_option(parser)
    return parser.parse_args()
Пример #8
0
def __get_options():
    """Return curve_to_lut option parser

    Returns:
        .argparse.ArgumentParser.args

    """
    # Define parser
    description = ('Create lut file corresponding to a colorspace or gamma '
                   'gradation')
    parser = argparse.ArgumentParser(description=description)
    # RGB colorspace
    action = parser.add_mutually_exclusive_group(required=True)
    action.add_argument("--colorspace",
                        help=("Input RGB Colorspace."),
                        type=str,
                        choices=sorted(COLORSPACES.keys() +
                                       PRIVATE_COLORSPACES.keys()))
    action.add_argument("--gamma",
                        help="Input pure gamma gradation",
                        type=float)
    # direction
    parser.add_argument("-d", "--direction", help=("Direction : "
                                                   "encode or decode."),
                        type=str, choices=[Direction.ENCODE, Direction.DECODE],
                        default=Direction.ENCODE)
    # out lut file, type, format, ranges,  out bit depth, out cube size
    add_outlutfile_option(parser, required=True)
    add_export_lut_options(parser)
    parser.add_argument("--process-input-range", action="store_true",
                        help=("If true, input range will be computed from "
                              " colorspace gradation functions."
                              "(Colorspace only))"))
    # version
    full_version = debug_helper.get_imported_modules_versions(sys.modules,
                                                              globals())
    add_version_option(parser, description, __version__, full_version)
    # verbose
    add_silent_option(parser)
    # trace
    add_trace_option(parser)
    return parser.parse_args()
Пример #9
0
def __get_options():
    """ Return rgb_to_xyz option parser

    Returns:
        .argparse.ArgumentParser.args

    """
    # Define parser
    description = 'Print RGB -> XYZ matrix'
    parser = argparse.ArgumentParser(description=description)
    # RGB colorspace
    parser.add_argument("-c",
                        "--colorspace",
                        help=("Input RGB Colorspace."),
                        type=str,
                        choices=sorted(COLORSPACES.keys() +
                                       PRIVATE_COLORSPACES.keys()),
                        default='Rec709')
    # Output format
    parser.add_argument("-f",
                        "--format",
                        help=("Output formatting."),
                        type=str,
                        choices=['matrix', 'spimtx', 'simple'],
                        default='matrix')
    # version
    parser.add_argument('-v',
                        "--version",
                        action='version',
                        version='{0} - version {1}'.format(
                            description, __version__))
    # full version
    versions = debug_helper.get_imported_modules_versions(
        sys.modules, globals())
    versions = '{0} - version {1}\n\n{2}'.format(description, __version__,
                                                 versions)
    parser.add_argument('-V',
                        "--full-versions",
                        action=debug_helper.make_full_version_action(versions))
    return parser.parse_args()
Пример #10
0
def __get_options():
    """Return plot that chroma option parser

    Returns:
        .argparse.ArgumentParser.args

    """
    # Define parser
    description = 'Plot chromaticities in a xy or u\'v\' diagram'
    parser = argparse.ArgumentParser(description=description)
    # RGB colorspace
    parser.add_argument("-space", "--colorspace",
                        help=("RGB Colorspace."),
                        type=str, action='append', dest='colorspaces',
                        choices=sorted(COLORSPACES.keys() +
                                       PRIVATE_COLORSPACES.keys()))
    # Points
    parser.add_argument("-p", "--point", type=float, nargs=2,
                        metavar=('x', 'y'), action='append',
                        dest='points', help='Display an xy point')
    # Spectrum locus
    parser.add_argument("-spectrum", "--spectrum-locus", action="store_true",
                        help="Display spectrum locus")
    return parser
Пример #11
0
def __get_options():
    """ Return rgb_to_xyz option parser

    Returns:
        .argparse.ArgumentParser.args

    """
    # Define parser
    description = 'Print RGB -> XYZ matrix'
    parser = argparse.ArgumentParser(description=description)
    # RGB colorspace
    parser.add_argument("-c", "--colorspace",
                        help=("Input RGB Colorspace."),
                        type=str,
                        choices=sorted(COLORSPACES.keys() +
                                       PRIVATE_COLORSPACES.keys()),
                        default='Rec709')
    # Output format
    parser.add_argument("-f", "--format",
                        help=("Output formatting."),
                        type=str,
                        choices=['matrix', 'spimtx', 'simple'],
                        default='matrix')
    # version
    parser.add_argument('-v', "--version", action='version',
                        version='{0} - version {1}'.format(description,
                                                           __version__))
    # full version
    versions = debug_helper.get_imported_modules_versions(sys.modules,
                                                          globals())
    versions = '{0} - version {1}\n\n{2}'.format(description,
                                                 __version__,
                                                 versions)
    parser.add_argument('-V', "--full-versions",
                        action=debug_helper.make_full_version_action(versions))
    return parser.parse_args()
Пример #12
0
def curve_to_lut(colorspace, gamma, outlutfile, out_type=None, out_format=None,
                 input_range=None, output_range=None, out_bit_depth=None,
                 out_cube_size=None, verbose=False, direction=Direction.ENCODE,
                 preset=None, overwrite_preset=False,
                 process_input_range=False):
    """Export a LUT from a colorspace gradation function

    Args:
        colorspace (str): input colorspace. Mutually exclusive with gamma.
        See list of colorspaces in utils.colorspaces

        gamma (float): input gamma. Mutually exclusive with colorspace.

        out_type (str): 1D, 2D or 3D

        out_format (str): '3dl', 'csp', 'cube', 'lut', 'spi', 'clcc', 'json'...

        outlutfile (str): path to output LUT

    Kwargs:

        input_range ([int/float, int/float]): input range.
        Ex: [0.0, 1.0] or [0, 4095]

        output_range ([int/float, int/float]): output range.
        Ex: [0.0, 1.0] or [0, 4095]

        out_bit_depth (int): output lut bit precision (1D only).
        Ex : 10, 16, 32.

        out_cube_size (int): output cube size (3D only). Ex : 17, 32.

        verbose (bool): print log if true

        direction (Direction): encode or decode

        preset (dict): lut generic and sampling informations

        process_input_range (bool): If true, input range will be computed from
        colorspace gradation functions. Colorspace only"

    """
    # get colorspace function
    if colorspace is None and gamma is None:
        raise AttributeError("A colorspace or a gamma should be specified")
    if colorspace is not None and gamma is not None:
        raise AttributeError("Choose between a colorspace or a gamma")
    elif gamma is not None:
        # gamma mode
        if direction == Direction.DECODE:
            gradation = lambda value: gamma_to_lin(value, gamma)
            title = "Gamma{0}_to_lin".format(gamma)
        else:
            gradation = lambda value: lin_to_gamma(value, gamma)
            title = "Lin_to_gamma{0}".format(gamma)
    else:
        # colorspace mode
        try:
            colorspace_obj = dict(list(COLORSPACES.items()) +
                                  list(PRIVATE_COLORSPACES.items()))[colorspace]
        except KeyError:
            raise CurveToLUTException(("Unsupported {0} "
                                       "Colorspace!").format(colorspace))
        if direction == Direction.DECODE:
            gradation = colorspace_obj.decode_gradation
            title = "{0}_to_lin".format(colorspace)
        else:
            gradation = colorspace_obj.encode_gradation
            title = "Lin_to_{0}".format(colorspace)
    # get preset and write function
    if preset:
        write_function = get_write_function(preset, overwrite_preset,
                                            out_type, out_format,
                                            input_range,
                                            output_range,
                                            out_bit_depth,
                                            out_cube_size,
                                            verbose)
    elif out_type is None or out_format is None:
        raise CurveToLUTException("Specify out_type/out_format or a preset.")
    else:
        preset, write_function = get_preset_and_write_function(out_type,
                                                               out_format,
                                                               input_range,
                                                               output_range,
                                                               out_bit_depth,
                                                               out_cube_size)
    if preset[presets.TYPE] == '3D':
        print_warning_message(("Gradations and gamma functions are 1D / 2D"
                               " transformations. Baking them in a 3D LUT "
                               "may not be efficient. Are you sure ?"))
    # process file output
    if os.path.isdir(outlutfile):
        filename = "{0}{1}".format(title,
                                   preset[presets.EXT])
        outlutfile = os.path.join(outlutfile, filename)
    else:
        try:
            check_extension(outlutfile, preset[presets.EXT])
            outlutfile = outlutfile
        except LUTException as error:
            raise CurveToLUTException(("Directory doesn't exist "
                                       "or {0}").format(error))
    preset[presets.TITLE] = title
    if process_input_range:
        if colorspace:
            preset[presets.IN_RANGE] = get_input_range(colorspace_obj,
                                                       direction,
                                                       8)
        else:
            raise CurveToLUTException(("--process-input-range must be used"
                                       " with --colorspace."))
    if verbose:
        print("{0} will be written in {1}.".format(title, outlutfile))
        print("Final setting:\n{0}".format(presets.string_preset(preset)))
    # write
    message = write_function(gradation, outlutfile, preset)
    if verbose:
        print_success_message(message)
Пример #13
0
def curve_to_lut(colorspace,
                 outlutpath,
                 lut_type='1D_CUBE',
                 lut_range=None,
                 lutsize=16,
                 direction=Direction.ENCODE):
    """Export a LUT from a colorspace gradation function

    Args:
        colorspace (str): input colorspace

        lut_type (str): 1D_CUBE, 1D_CSP, 1D_SPI

        lut_range ([float, float]): LUT range boundaries

        lutsize (int): out LUT bit precision for 1D. Ex : 16 (bits)

        direction (Direction): encode or decode

    """
    # init
    if not lut_range:
        lut_range = [0, 1]
    samples_count = pow(2, lutsize)
    if lut_type == '1D_CUBE':
        ext = ".cube"
        write_function = write_1d_cube_lut
    elif lut_type == '1D_CSP':
        ext = ".csp"
        write_function = write_1d_csp_lut
    elif lut_type == '1D_SPI':
        ext = ".spi1d"
        write_function = lambda lutfile, values: write_1d_spi_lut(
            lutfile, values, lut_range)
    else:
        raise CurveToLUTException(("Unsupported export "
                                   "format: {0}").format(lut_type))
    # process file output
    if os.path.isdir(outlutpath):
        filename = "{0}_{1}{2}".format(direction, colorspace, ext)
        outlutfile = os.path.join(outlutpath, filename)
    else:
        try:
            check_extension(outlutpath, ext)
            outlutfile = outlutpath
        except LUTException as error:
            raise CurveToLUTException(("Directory doesn't exist "
                                       "or {0}").format(error))
    # get colorspace function
    try:
        colorspace_obj = (COLORSPACES.items() +
                          PRIVATE_COLORSPACES.items())[colorspace]
    except KeyError:
        raise CurveToLUTException(("Unsupported {0} "
                                   "Colorspace!").format(colorspace))
    if direction == Direction.DECODE:
        gradation = colorspace_obj.decode_gradation
    else:
        gradation = colorspace_obj.encode_gradation
    # create range
    input_range = linspace(lut_range[0], lut_range[1], samples_count)
    output_range = []
    for x in input_range:
        y = gradation(x)
        output_range.append(y)
    write_function(outlutfile, output_range)
    print "{0} was converted into {1}.".format(colorspace, outlutfile)
Пример #14
0
def __get_options():
    """Return curve_to_lut option parser

    Returns:
        .argparse.ArgumentParser.args

    """
    ## Define parser
    description = 'Create lut file corresponding to a colorspace gradation'
    parser = argparse.ArgumentParser(description=description)
    # RGB colorspace
    parser.add_argument("colorspace",
                        help=("Input RGB Colorspace."),
                        type=str,
                        choices=sorted(COLORSPACES.keys() +
                                       PRIVATE_COLORSPACES.keys()))
    # output lut
    parser.add_argument("outlutpath",
                        help=("path to the output LUT."
                              " Can be a file or a "
                              "directory."),
                        type=str)
    # type
    parser.add_argument("-t",
                        "--out-type",
                        help=("Output LUT type."),
                        type=str,
                        choices=['1D_CSP', '1D_CUBE', '1D_SPI'],
                        default='1D_CUBE')
    # in range
    parser.add_argument("-ir",
                        "--in-range",
                        help=("In range value."),
                        type=float,
                        default=0.0)
    # out range
    parser.add_argument("-or",
                        "--out-range",
                        help=("Out range value."),
                        type=float,
                        default=1.0)
    # out lut size
    parser.add_argument("-os",
                        "--out-lut-size",
                        help=("Output lut bit precision. Ex : 10, 16, 32."),
                        default=16,
                        type=int)
    # direction
    parser.add_argument("-d",
                        "--direction",
                        help=("Direction : "
                              "encode or decode."),
                        type=str,
                        choices=[Direction.ENCODE, Direction.DECODE],
                        default=Direction.ENCODE)
    # version
    parser.add_argument('-v',
                        "--version",
                        action='version',
                        version='{0} - version {1}'.format(
                            description, __version__))
    # full version
    versions = debug_helper.get_imported_modules_versions(
        sys.modules, globals())
    versions = '{0} - version {1}\n\n{2}'.format(description, __version__,
                                                 versions)
    parser.add_argument('-V',
                        "--full-versions",
                        action=debug_helper.make_full_version_action(versions))
    return parser.parse_args()
Пример #15
0
def curve_to_lut(colorspace, outlutpath, lut_type='1D_CUBE',
                 lut_range=None, lutsize=16, direction=Direction.ENCODE):
    """Export a LUT from a colorspace gradation function

    Args:
        colorspace (str): input colorspace

        lut_type (str): 1D_CUBE, 1D_CSP, 1D_SPI

        lut_range ([float, float]): LUT range boundaries

        lutsize (int): out LUT bit precision for 1D. Ex : 16 (bits)

        direction (Direction): encode or decode

    """
    # init
    if not lut_range:
        lut_range = [0, 1]
    samples_count = pow(2, lutsize)
    if lut_type == '1D_CUBE':
        ext = ".cube"
        write_function = write_1d_cube_lut
    elif lut_type == '1D_CSP':
        ext = ".csp"
        write_function = write_1d_csp_lut
    elif lut_type == '1D_SPI':
        ext = ".spi1d"
        write_function = lambda lutfile, values: write_1d_spi_lut(lutfile,
                                                                  values,
                                                                  lut_range)
    else:
        raise CurveToLUTException(("Unsupported export "
                                   "format: {0}").format(lut_type))
    # process file output
    if os.path.isdir(outlutpath):
        filename = "{0}_{1}{2}".format(direction, colorspace, ext)
        outlutfile = os.path.join(outlutpath, filename)
    else:
        try:
            check_extension(outlutpath, ext)
            outlutfile = outlutpath
        except LUTException as error:
            raise CurveToLUTException(("Directory doesn't exist "
                                       "or {0}").format(error))
    # get colorspace function
    try:
        colorspace_obj = (COLORSPACES.items() +
                          PRIVATE_COLORSPACES.items())[colorspace]
    except KeyError:
        raise CurveToLUTException(("Unsupported {0} "
                                   "Colorspace!").format(colorspace))
    if direction == Direction.DECODE:
        gradation = colorspace_obj.decode_gradation
    else:
        gradation = colorspace_obj.encode_gradation
    # create range
    input_range = linspace(lut_range[0], lut_range[1], samples_count)
    output_range = []
    for x in input_range:
        y = gradation(x)
        output_range.append(y)
    write_function(outlutfile, output_range)
    print "{0} was converted into {1}.".format(colorspace, outlutfile)
Пример #16
0
def curve_to_lut(colorspace, gamma, outlutfile, out_type=None, out_format=None,
                 input_range=None, output_range=None, out_bit_depth=None,
                 out_cube_size=None, verbose=False, direction=Direction.ENCODE,
                 preset=None, overwrite_preset=False,
                 process_input_range=False):
    """Export a LUT from a colorspace gradation function

    Args:
        colorspace (str): input colorspace. Mutually exclusive with gamma.
        See list of colorspaces in utils.colorspaces

        gamma (float): input gamma. Mutually exclusive with colorspace.

        out_type (str): 1D, 2D or 3D

        out_format (str): '3dl', 'csp', 'cube', 'lut', 'spi', 'clcc', 'json'...

        outlutfile (str): path to output LUT

    Kwargs:

        input_range ([int/float, int/float]): input range.
        Ex: [0.0, 1.0] or [0, 4095]

        output_range ([int/float, int/float]): output range.
        Ex: [0.0, 1.0] or [0, 4095]

        out_bit_depth (int): output lut bit precision (1D only).
        Ex : 10, 16, 32.

        out_cube_size (int): output cube size (3D only). Ex : 17, 32.

        verbose (bool): print log if true

        direction (Direction): encode or decode

        preset (dict): lut generic and sampling informations

        process_input_range (bool): If true, input range will be computed from
        colorspace gradation functions. Colorspace only"

    """
    # get colorspace function
    if colorspace is None and gamma is None:
        raise AttributeError("A colorspace or a gamma should be specified")
    if colorspace is not None and gamma is not None:
        raise AttributeError("Choose between a colorspace or a gamma")
    elif gamma is not None:
        # gamma mode
        if direction == Direction.DECODE:
            gradation = lambda value: gamma_to_lin(value, gamma)
            title = "Gamma{0}_to_lin".format(gamma)
        else:
            gradation = lambda value: lin_to_gamma(value, gamma)
            title = "Lin_to_gamma{0}".format(gamma)
    else:
        # colorspace mode
        try:
            colorspace_obj = dict(COLORSPACES.items() +
                                  PRIVATE_COLORSPACES.items())[colorspace]
        except KeyError:
            raise CurveToLUTException(("Unsupported {0} "
                                       "Colorspace!").format(colorspace))
        if direction == Direction.DECODE:
            gradation = colorspace_obj.decode_gradation
            title = "{0}_to_lin".format(colorspace)
        else:
            gradation = colorspace_obj.encode_gradation
            title = "Lin_to_{0}".format(colorspace)
    # get preset and write function
    if preset:
        write_function = get_write_function(preset, overwrite_preset,
                                            out_type, out_format,
                                            input_range,
                                            output_range,
                                            out_bit_depth,
                                            out_cube_size,
                                            verbose)
    elif out_type is None or out_format is None:
        raise CurveToLUTException("Specify out_type/out_format or a preset.")
    else:
        preset, write_function = get_preset_and_write_function(out_type,
                                                               out_format,
                                                               input_range,
                                                               output_range,
                                                               out_bit_depth,
                                                               out_cube_size)
    if preset[presets.TYPE] == '3D':
        print_warning_message(("Gradations and gamma functions are 1D / 2D"
                               " transformations. Baking them in a 3D LUT "
                               "may not be efficient. Are you sure ?"))
    # process file output
    if os.path.isdir(outlutfile):
        filename = "{0}{1}".format(title,
                                   preset[presets.EXT])
        outlutfile = os.path.join(outlutfile, filename)
    else:
        try:
            check_extension(outlutfile, preset[presets.EXT])
            outlutfile = outlutfile
        except LUTException as error:
            raise CurveToLUTException(("Directory doesn't exist "
                                       "or {0}").format(error))
    preset[presets.TITLE] = title
    if process_input_range:
        if colorspace:
            preset[presets.IN_RANGE] = get_input_range(colorspace_obj,
                                                       direction,
                                                       8)
        else:
            raise CurveToLUTException(("--process-input-range must be used"
                                       " with --colorspace."))
    if verbose:
        print "{0} will be written in {1}.".format(title, outlutfile)
        print "Final setting:\n{0}".format(presets.string_preset(preset))
    # write
    message = write_function(gradation, outlutfile, preset)
    if verbose:
        print_success_message(message)