Color API
coloraide.NaN
- Description
NaNis a convenience constant forfloat('nan').- Import path
-
NaNis imported from thecoloraidelibrary:from coloraide import NaN
coloraide.stop
class stop:
def __init__(
self,
color: ColorInput,
value: float
) -> None:
...
- Description
stopobjects are used ininterpolatemethods. They allow a user to specify a color stop for a given color during the interpolation process.- Import Path
-
stopis imported fromcoloraidelibrary:from coloraide import stop - Parameters
-
Parameters Defaults Description colorA color string, a dictionary describing the color, or another Colorclass object.valueA numerical value specifying the new color stop for the given color.
coloraide.hint
def hint(
mid: float,
) -> Callable[..., float]:
...
- Description
hintreturns an easing function that adjust the midpoint between two color stops.- Import Path
-
hintis imported fromcoloraidelibrary:from coloraide import hint - Parameters
-
Parameters Defaults Description midA numerical value, relative to the two color stops it occurs between. The value will be used as the new midpoint.
coloraide.Color
class Color:
def __init__(
self,
color: ColorInput,
data: VectorLike | None = None,
alpha: float = util.DEF_ALPHA,
**kwargs: Any
) -> None:
...
- Description
- The
Colorclass object is a wrapper around the internal color space objects.Coloris the base Color object and only registers a select number of color spaces by default. It provides an API interface to allow users to specify and manipulate colors. - Import path
-
Coloris imported from thecoloraidelibrary:from coloraide import Color - Parameters
-
Parameters Defaults Description colorA color string, a dictionary describing the color, or another Colorclass object. If givendata, a string must be used and should represent the color space to use.dataNonedataaccepts a list of numbers representing the coordinates of the color. If provided,colormust be a string specifying the color space.alpha1alphaaccepts a number specifying thealphachannel. Must be used in conjunction withdataor it will be ignored.
coloraide.everything.ColorAll
class ColorAll(Color):
def __init__(
self,
color: ColorInput,
data: VectorLike | None = None,
alpha: float = util.DEF_ALPHA,
**kwargs: Any
) -> None:
...
- Description
- The
ColorAllclass object is derived fromColorand extends the registered color spaces to include all offered by ColorAide. - Import path
-
ColorAllis imported from thecoloraidelibrary:from coloraide.everything import ColorAll - Parameters
-
Parameters Defaults Description colorA color string, a dictionary describing the color, or another ColorAllclass object. If givendata, a string must be used and should represent the color space to use.dataNonedataaccepts a list of numbers representing the coordinates of the color. If provided,colormust be a string specifying the color space.alpha1alphaaccepts a number specifying thealphachannel. Must be used in conjunction withdataor it will be ignored.
Color.register
def register(
cls,
plugin: Plugin | Sequence[Plugin],
*,
overwrite: bool = False,
silent: bool = False
) -> None:
...
- Description
- Register a plugin(s).
- Parameters
-
Parameters Defaults Description pluginA plugin instance or list of plugin instances to register. overwriteFalseoverwritewill allow an already registered plugin to be overwritten if the plugin to register specifies anamethat is already used for registration.silentFalsesilentwill avoid throwing an error if thenameis already found andoverwriteis set toFalsein the specified category.
Color.deregister
@classmethod
def deregister(
cls,
plugin: str | Sequence[str], *,
silent: bool = False
) -> None:
...
- Description
- Remove an already registered plugin(s).
- Parameters
-
Parameters Defaults Description pluginA string or list of strings that describe the plugin(s) to be removed. Strings should be in the format category:namewherecategoryis eitherspace,delta-e,cat,filter,contrast,interpolate, orfitandnameis the name the plugin was registered under.*will remove all plugins andcategory:*will remove all within a specific category.silentFalsesilentwill avoid throwing an error if thenamecan not be found in the specified category.
Color.match
@classmethod
def match(
cls,
string: str,
start: int = 0,
fullmatch: bool = False
) -> ColorMatch | None:
...
- Description
-
The
matchclass method provides access to the color matching interface and allows a user to provide a color string and get back aColorMatchobject.ColorMatchobjects contain three properties:class ColorMatch: def __init__( self, color: Color, start: int, end: int ) -> None: ...Parameter Description colorThe Colorobject.startThe starting point within the string buffer where the color was found. endThe ending point within the string buffer where the color was found. Match does not search the entire buffer, but simply matches at the location specified by
start. - Parameters
-
Parameters Defaults Description stringA string representing the color. start0Accepts an integer offset into the provided string buffer to start the match. fullmatchFalseA boolean which defines whether match must match to the end of the string buffer. - Return
- Returns a
ColorMatchobject.
Color.new
@classmethod
def new(
cls,
color: ColorInput,
data: VectorLike | None = None,
alpha: float = util.DEF_ALPHA,
**kwargs: Any
) -> Self:
...
- Description
- The
newclass method exposes the interface of creating new color objects. Usingnewis the same as usingColor(). - Parameters
-
Parameters Defaults Description colorA color string, or other Colorclass object. If givendata, a string must be used and should represent the color space to use.dataNonedataaccepts a list of numbers representing the coordinates of the color. If provided,colormust be a string specifying the color space.alpha1alphaaccepts a number specifying thealphachannel. Must be used in conjunction withdataor it will be ignored. - Return
- Returns a
Colorobject.
Color.random
@classmethod
def random(
cls,
space: str,
*,
limits: Sequence[Sequence[float] | None] | None = None
) -> Self:
...
- Description
- Generate a random color in the provided
space. The color space's channel range will be used as a limit for the channel. For color spaces with no clearly defined gamut, these values can be arbitrary. In such cases, it may be advisable to fit the returned color space to a displayable gamut. - Parameters
-
Parameters Defaults Description spaceThe color space name in which to generate a random color in. limitsNoneAn optional list of constraints for various color channels. Each entry should either be a sequence contain a minimum and maximum value, or should be None.Nonevalues will be ignored and the color space's specified channel range will be used instead. Any missing entries will be treated asNone. - Return
- Returns a
Colorobject.
Color.clone
def clone(
self
):
...
- Description
- The
clonemethod provides a way to create a duplicate of the currentColorinstance. - Return
- Returns a
Colorobject.
Color.update
def update(
self,
color: ColorInput,
data: VectorLike | None = None,
alpha: float = util.DEF_ALPHA,
*,
norm: bool = True,
**kwargs: Any
) -> Self:
...
- Description
- The
updatemethod provides a way to update the underlying color space with coordinates from any color space. The method's signature is the same asnewexcept that it adds an additionalnormparameter used to skip achromatic hue normalization when converting to the current color space. The object itself will assume the equivalent color in the current color space that matches the input color's value (assuming no algorithmic limitations preventing an equivalent color). - Parameters
-
Parameters Defaults Description colorA color string, or other Colorclass object. If givendata, a string must be used and should represent the color space to use.dataNonedataaccepts a list of numbers representing the coordinates of the color. If provided,colormust be a string specifying the color space.alpha1alphaaccepts a number specifying thealphachannel. Must be used in conjunction withdataor it will be ignored.normTrueWhen set to False, this prevents achromatic normalization when updating from a different color space. If no update occurs, nothing is done. - Return
- Returns a reference to the current
Colorobject.
Color.mutate
def mutate(
self,
color: ColorInput,
data: VectorLike | None = None,
alpha: float = util.DEF_ALPHA,
**kwargs: Any
) -> Self:
...
- Description
- The
mutatemethod is similar toupdateexcept that it does not convert the input color to the current color space, but instead replaces the current color space and values with the input color's color space and values. - Parameters
-
Parameters Defaults Description colorA color string, or other Colorclass object. If givendata, a string must be used and should represent the color space to use.dataNonedataaccepts a list of numbers representing the coordinates of the color. If provided,colormust be a string specifying the color space.alpha1alphaaccepts a number specifying thealphachannel. Must be used in conjunction withdataor it will be ignored. - Return
- Returns a reference to the current
Colorobject.
Color.convert
def convert(
self,
space: str,
*,
in_place: bool = False,
norm: bool = True
) -> Self:
...
- Description
- Converts a
Colorobject from one color space to another. If the current color space matches the specified color space, a clone of the current color will be returned with no changes to the channel values. Ifin_placeisTrue, the current object will be modified in place. - Parameters
-
Parameters Defaults Description spaceA string representing the desired final color space. in_placeFalseBoolean specifying whether the convert should alter the current Colorobject or return a new one.normTrueWhen set to False, this prevents achromatic normalization when converting from a different color space. If no update occurs, nothing is done. - Return
- Returns a reference to the converted
Colorobject. Ifin_placeisTrue, the return will be a reference to the currentColorobject.
Color.space
def space(
self
) -> str:
...
- Description
- Retrieves the current color space name as specified by the underlying color space object.
- Return
- Returns a string with the name of the current color space.
Color.normalize
def normalize(
self,
*,
nans: bool = True
) -> Self:
...
- Description
- Force normalization of a color's channels by forcing cylindrical colors with negative chroma/saturation to their positive form and setting hue to undefined if the color is achromatic. If
nansis set toFalse, the hue normalization step (setting hue to undefined) will be skipped. Normalize modifies the current color in place. - Parameters
-
Parameters Defaults Description nansTruePerform hue normalization (setting hue to undefined if the color is achromatic). - Return
- Returns a reference to the current
Colorobject after normalizing the channels for undefined hues.
Color.to_dict
def to_dict(
self,
*,
nans: bool = True,
precision: int | Sequence[int] | None = None,
decimal: int | bool | Sequence[int | bool] | None = None
) -> Mapping[str, Any]:
...
- Description
-
Dump the color object to a simple dictionary.
{ 'space': 'srgb', # Color space name 'coords': [1.0, 0.0, 0.0], # Color channel values 'alpha': 1.0 # Alpha channel value } - Parameters
-
Parameters Defaults Description nansTrueReturn channel values having undefined values resolved as defined values. precisionNoneReturn value rounded to the specified significant figures. 0will result in integer rounding. IfNone, the default will be used. If the precision is a sequence, each returned coordinate will be rounded according to the precision at the corresponding index in the sequence.decimalNoneReturn value rounded to the specific decimal point. If None, the default will be used. If the decimal is a sequence, each returned coordinate will be rounded according to the decimal at the corresponding index in the sequence. - Return
- A dictionary containing the color space name and channel values.
Color.to_string
def to_string(
self,
**kwargs: Any
) -> str:
...
- Description
- Method that converts the current color to an output format supported by the color space. While a number of the parameters are common, some may be specific to the color space. The usage guide covers color space specific options in more details.
- Parameters
-
Common parameters:
Parameters Defaults Description alphaNoneBoolean or Nonevalue which determines whether the output includesalpha. IfNone, the default alpha will only be shown if less than 1. IfTrue, alpha will always be shown. IfFalse, alpha will be omitted.precision5Integer value that sets precision and scale. Precision and scale will match the value if greater than zero. If 0, values will be rounded to the nearest integer. If-1, number will be output at the highest precision.fitTrueA boolean that controls whether gamut mapping is performed on string creation. By default, colors will be fit to their own color space. This can be disabled by setting to False.colorFalseA boolean that will determine if the color(space coord+ / alpha)format is used for string output. Has highest precedence.percentVaries A boolean that will output color channels as percents. Not all color spaces support percents, or may support percents only in certain scenarios. Default value may be determined by the color space. sRGB specific parameters:
Parameters Defaults Description hex.FalseString output will be in #RRGGBBAAformat.namesFalseBoolean indicating a preference for CSS color names. When translating a color to it's closest hex form, if that hex value matches a CSS color name, that color name will be returned as the output. hexdoes not have to beTruefor this to apply.compressFalseIf hexisTrueandcompressisTrue, hex values will be compressed if possible:#RRGGBBAA→#RGBA.Space dependent parameters:
Parameters Defaults Description commaFalseIf supported by the color space and the current output format, commas will be used instead of space format: rgba(0, 0, 0, 1)→rgb(0 0 0 /1). - Return
- Returns a string representation of the current color.
Color.luminance
def luminance(
self,
*,
white: VectorLike | None = cat.WHITES['2deg']['D65']
) -> float:
...
- Description
- Get the relative luminance. Relative luminance is obtained from the Y coordinate in the XYZ color space. XYZ, in this case, has a D65 white point.
- Parameters
-
Parameters Defaults Description whiteNoneSpecify the white in which to chromatically adapt the points from, if none is specified, the current color's white point is assumed. - Return
- Returns an float indicating the relative luminance.
Color.contrast
def contrast(
self,
color: ColorInput,
method: str | None = None
) -> float:
...
- Description
- Get the contrast ratio based on the relative luminance between two colors.
- Parameters
-
Parameters Defaults Description colorA color string, Colorobject, or dictionary representing a color.methodNoneSpecify the method used to obtain the contrast value. If None, the default specified by the class will be used. - Return
- Returns a float indicating the contrast ratio between two colors.
Color.distance
def distance(
self,
color: ColorInput,
*,
space: str = "lab"
) -> float:
...
- Description
- Performs a euclidean distance algorithm on two colors.
- Parameters
-
Parameters Defaults Description colorA color string, Colorobject, or dictionary representing a color.space"lab"Color space to perform distancing algorithm in. - Return
- Returns a float indicating euclidean distance between the two colors.
Color.delta_e
def delta_e(
self,
color: ColorInput,
*,
method: str | None = None,
**kwargs: Any
) -> float:
...
- Description
-
Performs a delta E distance algorithm on two colors. Default algorithm that is used is Delta E 1976 (
76). Some methods have additional weighting that can be configured through method specific options which are represented by**kwargs.Available methods:
Name Input Parameters ∆E*ab (CIE76) 76∆E*cmc (CMC l:c (1984)) cmcl=2, c=1∆E*94 (CIE94) 94kl=1, k1=0.045, k2=0.015∆E*00 (CIEDE2000) 2000kl=1, kc=1, kh=1∆EHyAB (HyAB) hyabspace="lab"∆Eok okscalar=1∆Eitp (ICtCp) itpscalar=720∆Ez (Jzazbz) jz∆E99o (DIN99o) 99o∆Ecam16 cam16model=ucs∆EHCT hct - Parameters
-
Parameters Defaults Description colorA color string, Colorobject, or dictionary representing a color.methodNoneString that specifies the method to use. If None, the default will be used.**kwargsAny distancing specific parameters to pass to ∆E method. - Return
- Returns a float indicating the delta E distance between the two colors.
Color.closest
def closest(
self,
colors: Sequence[ColorInput],
*,
method: str | None = None,
**kwargs: Any
) -> Self:
...
- Description
- Given a list of colors, calculates the closest color to the calling color object.
- Parameters
-
Parameters Defaults Description colorsA list of color strings, Colorobject, or dictionary representing a color.methodNoneString that specifies the method of color distancing to use. **kwargsAny distancing specific parameters to pass to ∆E method. - Return
- The
Colorthat is closest to the calling color object. In the off chance that an empty list is passed inNonewill be returned.
Color.mask
def mask(
self,
channel: str | Sequence[str],
*,
invert: bool = False,
in_place: bool = False
) -> Self:
...
- Description
- The
maskmethod will set any and all specified channels toNaN. Ifinvertis set toTrue,maskwill set any and all channels not specified toNaN. - Parameters
-
Parameters Defaults Description channelA string specifying a channel, or a list of strings specifying multiple channels. Specified channels will be masked (or the only channels not masked if invertisTrue).invertFalseUse inverse masking logic and mask all channels that are not specified. in_placeFalseBoolean used to determine if the current color should be modified "in place" or a new Colorobject should be returned. - Return
- Returns a reference to the masked
Colorobject. Ifin_placeisTrue, the return will be a reference to the currentColorobject.
Color.interpolate
@classmethod
def interpolate(
cls,
colors: Sequence[ColorInput | interpolate.stop | Callable[..., float]],
*,
space: str | None = None,
out_space: str | None = None,
progress: Mapping[str, Callable[..., float]] | Callable[..., float] | None = None,
hue: str = util.DEF_HUE_ADJ,
premultiplied: bool = True,
extrapolate: bool = False,
domain: list[float] | None = None,
method: str = "linear",
padding: float | tuple[float, float] | None = None,
carryforward: bool | None = False,
powerless: bool | None = False,
**kwargs: Any
) -> Interpolator:
...
- Description
-
The
interpolatemethod creates a function that takes a value between 0 - 1 and interpolates a new color based on the input value.If more than one color is provided, the returned function will span the interpolations between all the provided colors with the same range of 0 - 1.
Interpolation can be customized by limiting the interpolation to specific color channels, providing custom interpolation functions, and even adjusting the hue logic used.
stopobjects can wrapped around colors to specify new color stops and easing functions can be placed between colors to alter the transition progress between the two colors.Hue Evaluation Description shorterAngles are adjusted so that θ₂ - θ₁ ∈ [-180, 180]. longerAngles are adjusted so that θ₂ - θ₁ ∈ {[-360, -180], [180, 360]}. increasingAngles are adjusted so that θ₂ - θ₁ ∈ [0, 360]. decreasingAngles are adjusted so that θ₂ - θ₁ ∈ [-360, 0] specifiedNo fixup is performed. Angles are interpolated in the same way as every other component. The method of interpolation to can also be selected via the
methodparameter.Method Description linearAn linear interpolation that employs piecewise logic to interpolate between two or more colors. bsplineAn interpolation method that employs cubic B-spline curves to calculate an interpolation path through multiple colors. naturalA natural interpolation spline based on the cubic B-spline curve. monotoneAn interpolation method that utilizes a monotonic cubic spline based on the Hermite spline. catromInterpolation based on the Catmull-Rom cubic spline. - Parameters
-
Parameters Defaults Description colorsA list of color strings, Colorobjects, dictionaries representing a color,stopobjects, or easing functions.space"lab"Color space to interpolate in. out_spaceNoneColor space that the new color should be in. If None, the return color will be in the same color space as specified byspace.progressNoneAn optional function that allows for custom logic to perform non-linear interpolation. hue"shorter"Define how color spaces which have hue angles are interpolated. Default evaluates between the shortest angle. premultipliedTrueUse premultiplied alpha when interpolating. extrapolateFalseInterpolations should extrapolate when values exceed the domain range ([0, 1] by default). domainNoneA list of numbers defining the domain range of the interpolation. method"linear"The interpolation method to use. paddingNoneAdjust the padding of the interpolation range. carryforwardFalseCarry forward undefined channels when converting to the interpolation space. If None, will use the class default which isFalseby default.powerlessNoneTreat explicitly defined hues as powerless when the color is considered achromatic. If None, will use the class default which isFalseby default. - Return
- Returns a function that takes a range within the specified domain, the default being
[0..1]. The function returns a new, interpolatedColorobject.
Color.steps
@classmethod
def steps(
cls,
colors: Sequence[ColorInput | interpolate.stop | Callable[..., float]],
*,
steps: int = 2,
max_steps: int = 1000,
max_delta_e: float = 0,
delta_e: str | None = None,
delta_e_args: dict[str, Any] | None = None,
**interpolate_args: Any
) -> list[Self]:
...
- Description
-
Creates an
interpolatefunction and iterates through it with user defined step parameters to produce discrete color steps. Will attempt to provide the minimum number ofstepswithout exceedingmax_steps. Ifmax_delta_eis provided, the distance between each stop will be cut in half until there are no colors with a distance greater than the specifiedmax_delta_e. The default ∆E method is used by default, but it can be changed with thedelta_eparameter.If more than one color is provided, the steps will be returned from the interpolations between all the provided colors.
Like
interpolate, the default interpolation space islab. - Parameters
-
Parameters Defaults Description colorA list of color strings, Colorobjects, dictionaries representing a color,stopobjects, or easing functions.steps2Minimum number of steps. max_steps1000Maximum number of steps. max_delta_e0Maximum delta E distance between the color stops. A value of 0or less will be ignored.delta_eNoneA string indicating which ∆E method to use. If nothing is supplied, the class object's current default ∆E method will be used. delta_e_argsNoneA dictionary containing keyword arguments to be passed to the delta_emethod.**interpolate_argsSee interpolateKeyword arguments defined in interpolate. - Return
- List of
Colorobjects.
Color.discrete
@classmethod
def discrete(
cls,
colors: Sequence[ColorInput | interpolate.stop | Callable[..., float]],
*,
space: str | None = None,
out_space: str | None = None,
steps: int | None = None,
max_steps: int = 1000,
max_delta_e: float = 0,
delta_e: str | None = None,
delta_e_args: dict[str, Any] | None = None,
domain: list[float] | None = None,
**interpolate_args: Any
) -> Interpolator[Self]:
...
- Description
-
Generates an
interpolatefunction with discrete color scale. By default it assumes as many discrete colors as the user inputs, butstepscan be used to generate more or less using the input colors. Asdiscreteis built onsteps, it takes all the same arguments.Like
interpolate, the default interpolation space islab. - Parameters
-
Parameters Defaults Description colorA list of color strings, Colorobjects, dictionaries representing a color,stopobjects, or easing functions.space"lab"Color space to interpolate in. out_spaceNoneColor space that the new color should be in. If None, the return color will be in the same color space as specified byspace.stepsNoneMinimum number of steps. If None, steps will be set to the number of input colors.max_steps1000Maximum number of steps. max_delta_e0Maximum delta E distance between the color stops. A value of 0or less will be ignored.delta_eNoneA string indicating which ∆E method to use. If nothing is supplied, the class object's current default ∆E method will be used. delta_e_argsNoneA dictionary containing keyword arguments to be passed to the delta_emethod.domainNoneA list of numbers defining the domain range of the interpolation. **interpolate_argsSee interpolateKeyword arguments defined in interpolate. - Return
- Returns a function that takes a range within the specified domain, the default being
[0..1]. The function returns a new, interpolatedColorobject.
Color.mix
def mix(
self,
color: ColorInput,
percent: float = util.DEF_MIX,
*,
in_place: bool = False,
**interpolate_args: Any
) -> Self:
...
- Description
- Interpolates between two colors returning a color that represents the mixing of the base color and the provided
colormixed at the providedpercent, wherepercentapplies to how much the providedcolorcontributes to the final result. - Parameters
-
Parameters Defaults Description colorA color string, Colorobject, or dictionary representing a color.percent0.5A numerical value between 0 - 1 representing the percentage at which the parameter colorwill be mixed.in_placeFalseBoolean used to determine if the current color should be modified "in place" or a new Colorobject should be returned.**interpolate_argsSee interpolateKeyword arguments defined in interpolate. - Return
- Returns a reference to the new
Colorobject or a reference to the currentColorifin_placeisTrue.
Color.average
@classmethod
def average(
cls,
colors: Iterable[ColorInput],
weights: Iterable[float] | None = None,
*,
space: str | None = None,
out_space: str | None = None,
premultiplied: bool = True,
powerelss: bool | None = None
**kwargs: Any
) -> Self:
...
- Description
- Get the average mean of all channels given a particular set of input colors.
- Parameters
-
Parameters Defaults Description colorsAn iterable of color strings, Colorobjects, and/or dictionaries representing a color.weightsNoneAn iterable of floats representing weights for the given colors.spaceNoneAn optional string to specify what color space the colors should be averaged in. If none is provided, Oklab is assumed. out_spaceNoneColor space that the new color should be in. If None, the return color will be in the same color space as specified viaspace.premultipliedTrueSpecify whether colors should be premultiplied during the averaging process. powerlessNoneTreat explicitly defined hues as powerless when the color is considered achromatic. If None, will use the class default which isFalseby default. - Return
- Returns a reference to the new
Colorobject representing the average of the input colors.
Deprecated 4.1
powerless parameter has been deprecated in 4.1 and as it is now always enabled. The parameter no longer does anything and will be removed in the future.
Color.filter
def filter(
self,
name: str,
amount: float | None = None,
*,
space: str | None = None,
in_place: bool = False,
out_space: str | None = None,
**kwargs: Any
) -> Self:
...
- Description
-
Apply a color filter to alter a given color. The non-CVD filters are based on the W3C Filter Effects and behave in the same manner. Colors are evaluated in the sRGB Linear color space unless otherwise specified via the
spaceparameter. No other color space will be accepted except sRGB and sRGB Linear.An
amountcan be provided to adjust how much the color is filtered. Any clamping that occurs with theamountparameter, and related ways in whichamountare applied, follow the W3C Filter Effects spec.Some filters, such as CVDs, may take additional arguments via
kwargs.Filters Name Default Brightness brightness1Saturation saturate1Contrast contrast1Opacity opacity1Invert invert1Hue rotation hue-rotate0Sepia sepia1Grayscale grayscale1CVD Filters Name Default Protanopia CVD protan1Deuteranopia CVD deutan1Tritanopia CVD tritan1 - Parameters
-
Parameters Defaults Description nameThe name of the filter that should be applied. amountSee above A numerical value adjusting to what degree the filter is applied. Input range can vary depending on the filter being used. Default can also dependent on the filter being used. spaceNoneControls the algorithm used for simulating the given CVD. in_placeFalseBoolean used to determine if the current color should be modified "in place" or a new Colorobject should be returned.out_spaceNoneColor space that the new color should be in. If None, the return color will be in the same color space as specified viaspace.**kwargsAdditional filter specific parameters. CVDs also take an optional
methodparameter that allows for specifying the CVD algorithm to use.Simulation Approach Name Brettel 1997 brettelViénot, Brettel, and Mollon 1999 vienotMachado 2009 machado - Return
- Returns a reference to the new
Colorobject or a reference to the currentColorifin_placeisTrue.
Color.harmony
def harmony(
self,
name: str,
*,
space: str | None = None,
out_space: str | None = None,
**kwargs: Any
) -> list[Self]:
...
- Description
-
The
harmonymethod uses the current color and returns a set of harmonious colors (including the current color). The color harmonies are based on the classical color harmonies of color theory. By default, harmonious colors are selected under the perceptually uniform OkLCh color space, but other cylindrical color spaces can be used.Harmony Name Monochromatic monoComplementary complementSplit Complement splitAnalogous analogousTriadic triadTetradic Square squareTetradic Rectangle rectangleWheel wheel - Parameters
-
Parameters Defaults Description nameName of the color harmony to use. space'oklch'Color space under which the harmonies will be calculated. Must be a cylindrical space. out_spaceNoneColor space that the new color should be in. If None, the return color will be in the same color space as specified viaspace.**kwargsAny harmony specific parameters to pass to the called harmony. - Return
- Returns a list of
Colorobjects.
Color.compose
Deprecated 4.0
compose method was deprecated in favor of the new layer method and will be removed at some future time.
def compose(
self,
backdrop: ColorInput | Sequence[ColorInput],
*,
blend: str | bool = True,
operator: str | bool = True,
space: str | None = None,
out_space: str | None = None,
in_place: bool = False
) -> Self:
...
- Description
-
Apply compositing which consists of a blend mode and a Porter Duff operator for alpha compositing. The current color is treated as the source (top layer) and the provided color as the backdrop (bottom layer). Colors will be composited in the
srgbcolor space unless otherwise specified.Compositing should generally be applied in RGB-ish color spaces (sRGB, Display P3, A98 RGB, etc.). The algorithm is designed only for RGB-ish colors. Non-RGB-ish colors are likely to provide nonsense results.
Supported blend modes are:
Blend Modes normalmultiplydarkenlightenburndodgescreenoverlayhard-lightexclusiondifferencesoft-lighthuesaturationluminositycolorcolorhuesaturationluminositySupported Port Duff operators are:
Operators clearcopydestinationsource-overdestination-oversource-indestination-insource-outdestination-outsource-atopdestination-atopxorlighter - Parameters
-
Parameters Defaults Description backdropA background color or sequence of background colors represented with strings, Colorobjects, and/or dictionaries representing a color.blendNoneA blend mode to use to use when compositing. Values should be a string specifying the name of the blend mode to use. If None,normalwill be used. IfFalse, blending will be skipped.operatorNoneA Porter Duff operator to use for alpha compositing. Values should be a string specifying the name of the operator to use. If None,source-overwill be used. IfFalse, alpha compositing will be skipped.spaceNoneA color space to perform the overlay in. If None, the base color's space will be used.out_spaceNoneColor space that the new color should be in. If None, the return color will be in the same color space as specified byspace.in_placeFalseBoolean used to determine if the current color should be modified "in place" or a new Colorobject should be returned. - Return
- Returns a reference to the new
Colorobject or a reference to the currentColorifin_placeisTrue.
Color.layer
@classmethod
def layer(
cls,
colors: Sequence[ColorInput],
*,
blend: str | bool = True,
operator: str | bool = True,
space: str | None = None,
out_space: str | None = None
) -> Self:
...
- Description
-
Layer colors on time of each other and apply compositing which consists of a blend mode and a Porter Duff operator for alpha compositing. Colors are provided in a list where the left most color is treated as the top most color and the right most color is treated as the bottom most color. Colors will be composited in the
srgbcolor space unless otherwise specified.Compositing should generally be applied in RGB-ish color spaces (sRGB, Display P3, A98 RGB, etc.). The algorithm is designed only for RGB-ish colors. Non-RGB-ish colors are likely to provide nonsense results.
Supported blend modes are:
Blend Modes normalmultiplydarkenlightenburndodgescreenoverlayhard-lightexclusiondifferencesoft-lighthuesaturationluminositycolorcolorhuesaturationluminositySupported Port Duff operators are:
Operators clearcopydestinationsource-overdestination-oversource-indestination-insource-outdestination-outsource-atopdestination-atopxorlighter - Parameters
-
Parameters Defaults Description colorsA sequence of color strings, Colorobjects, and/or dictionaries representing a color.blendNoneA blend mode to use to use when compositing. Values should be a string specifying the name of the blend mode to use. If None,normalwill be used. IfFalse, blending will be skipped.operatorNoneA Porter Duff operator to use for alpha compositing. Values should be a string specifying the name of the operator to use. If None,source-overwill be used. IfFalse, alpha compositing will be skipped.spaceNoneA color space to perform the overlay in. If None, the base color's space will be used.out_spaceNoneColor space that the new color should be in. If None, the return color will be in the same color space as specified byspace. - Return
- Returns a reference to the new
Colorobject.
Color.clip
def clip(
self,
space: str | None = None
) -> Self:
...
- Description
- Performs simple clipping on color channels that are out of gamut.
- Parameters
-
Parameters Defaults Description spaceNoneThe color space that the color must be mapped to. If space is None, then the current color space will be used. - Return
- Returns a reference to the current
Colorafter fitting its coordinates to the specified gamut.
Color.fit
def fit(
self,
space: str | None = None,
*,
method: str | None = None,
**kwargs: Any
) -> Self:
...
- Description
-
Fits color to the current or specified color gamut.
By default,
lch-chromagamut mapping is used. This is essentially an approach that holds lightness and hue constant in the CIELCh color space while reducing chroma until the color is in gamut. Clipping is done at each step of the way and the color distance measured to see how close our color is to the intended color.The supported gamut mapping methods are:
Name Input Clipping clipOkLCh Chroma oklch-chromaLCh Chroma lch-chroma - Parameters
-
Some methods could have additional parameters to configure the behavior, these would be done through
**kwargs. None of built-in gamut mapping methods currently have additional parameters.Parameters Defaults Description spaceNoneThe color space that the color must be mapped to. If space is None, then the current color space will be used.methodNoneString that specifies which gamut mapping method to use. If None,lch-chromawill be used. - Return
- Returns a reference to the current
Colorafter fitting its coordinates to the specified gamut.
Color.in_gamut
def in_gamut(
self, space: str | None = None,
*,
tolerance: float = util.DEF_FIT_TOLERANCE
) -> bool:
...
- Description
- Checks if the current color is in the current or specified gamut.
- Parameters
-
Parameters Defaults Description spaceNoneThe color space that the color must be fit within. If space is None, then the current color space will be used.tolerance0.000075Tolerance allowed when checking bounds of color. - Return
- Returns a boolean indicating whether the color is in the specified gamut.
Color.get
@overload
def get(self,
name: str,
*,
nans: bool = True,
precision: int | Sequence[int] | None = None,
decimal: int | bool | Sequence[int | bool] | None = None
) -> float:
...
@overload
def get(
self,
name: list[str] | tuple[str, ...],
*,
nans: bool = True,
precision: int | Sequence[int] | None = None,
decimal: int | bool | Sequence[int | bool] | None = None
) -> Vector:
...
def get(
self,
name: str | list[str] | tuple[str, ...],
*,
nans: bool = True,
precision: int | Sequence[int] | None = None,
decimal: int | bool | Sequence[int | bool] | None = None
) -> float | Vector:
...
- Description
- Retrieves the coordinate value from the specified channel or values from a sequence of specified channels. Channels must be a channel name in the current color space or a channel name in the specified color space using the syntax:
space.channel. - Parameters
-
Parameters Defaults Description nameChannel name or sequence of channel names. Channel names can define the color space and channel name to retrieve value from a different color space. nansTrueDetermines whether an undefined value is allowed to be returned. If disabled, undefined values will be resolved before returning. precisionNoneReturn value rounded to the specified significant figures. 0will result in integer rounding. IfNone, the default will be used. If the precision is a sequence, each returned coordinate will be rounded according to the precision at the corresponding index in the sequence.decimalNoneReturn value rounded to the specific decimal point. If None, the default will be used. If the decimal is a sequence, each returned coordinate will be rounded according to the decimal at the corresponding index in the sequence.Return -
Returns a numerical value that is stored internally for the specified channel, or a calculated value in the case that a channel in a different color space is requested. If more than one value is requested, the a list of numerical values will be returned.
Color.set
def set(
self,
name: str | dict[str, float | Callable[..., float]],
value: float | Callable[..., float] | None = None,
*,
nans: bool = True
) -> Self:
...
- Description
-
Sets the given value to the specified channel. If the
nameis provided in the formspace.channel, the value will be applied to the channel of the specified color space while keeping current color space the same.The
valuecan be a numerical value or a function that accepts a numerical channel value and returns a numerical channel value.namecan also be a dictionary of channels, each with avalue. In this case, thevalueparameter of the function can be ignored.This function returns the current colors reference so that multiple sets can be chained together.
- Parameters
-
Parameters Defaults Description nameA string containing a channel name or color space and channel separated by a .specifying the what channel to set. Ifvalueis omitted,namecan also be a dictionary containing multiple channels, each specifying their own value to set.valueA numerical value, a string value accepted by the specified color space, or a function. nansTrueWhen doing relative sets via a callback input, ensure the channel value passed to the callback is a real number, not an undefined value. - Return
- Returns a reference to the current
Colorobject.
Color.coords
def coords(
self,
*,
nans: bool = True,
precision: int | Sequence[int] | None = None,
decimal: int | bool | Sequence[int | bool] | None = None
) -> Vector:
...
- Description
- Get the color channels (no alpha). If
nansis set toFalse, all undefined values will be returned as defined. - Parameters
-
Parameters Defaults Description nansTrueIf nansis set toFalse, all undefined values will be returned as defined.precisionNoneReturn value rounded to the specified significant figures. 0will result in integer rounding. IfNone, the default will be used. If the precision is a sequence, each returned coordinate will be rounded according to the precision at the corresponding index in the sequence.decimalNoneReturn value rounded to the specific decimal point. If None, the default will be used. If the decimal is a sequence, each returned coordinate will be rounded according to the decimal at the corresponding index in the sequence. - Return
- Returns a list of
floatvalues, one for each color channel.
Color.alpha
def alpha(
self,
*,
nans: bool = True,
precision: int | None = None,
decimal: int | bool | None = None
) -> float:
...
- Description
- Get the alpha channel's value. If
nansis set toFalse, an undefined value will be returned as defined. - Parameters
-
Parameters Defaults Description nansTrueIf nansis set toFalse, an undefined value will be returned as defined.precisionNoneReturn value rounded to the specified significant figures. 0will result in integer rounding. IfNone, the default will be used.decimalNoneReturn value rounded to the specific decimal point. If None, the default will be used. - Return
- Returns a
float.
Color.is_achromatic
def is_achromatic(
self
) -> bool:
...
- Description
- Can be called on any color to determine if the color is achromatic. If a color is achromatic, or very close to achromatic, it will return
True. - Return
- Returns a boolean indicating whether the color is achromatic.
Color.is_nan
def is_nan(
self,
name: str
) -> bool:
...
- Description
- Retrieves the coordinate value from the specified channel and checks whether the value is undefined (set to NaN). Channel must be a channel name in the current color space or a channel name in the specified color space using the syntax:
space.channel. - Parameters
-
Parameters Defaults Description nameA string indicating what channel property to check. - Return
- Returns a boolean indicating whether the specified color space's channel is
NaN.
Color.white
def white(
self
) -> Vector:
...
- Description
- Retrieves the white point for the current color's color space.
- Return
- Returns a set of XYZ coordinates that align with the white point for the given color space.
Color.blackbody
@classmethod
def blackbody(
cls,
temp: float,
duv: float = 0.0,
*,
scale: bool = True,
scale_space: str | None = None,
out_space: str | None = None,
method: str | None = None,
**kwargs: Any
) -> Self:
...
- Description
- Creates a color from a temperature in Kelvin and an optional ∆uv. The color will be scaled within the linear RGB space specified by
scale_spaceand can be disabled by settingscaletoFalse. By default, the Ohno 2013 algorithm is used and can be configured viamethod. - Parameters
-
Parameters Defaults Description tempA positive temperature in Kelvin. Accepted range of temperature is based on the algorithm. duv0.0An optional ∆uv specifying the distance from the black body curve. scaleTrueScale the color with a linear RGB color space as defined by scale_space.scale_space'srgb-linear'If scaleis enabled,scale_spacedefines the RGB color space in which the returned color should be scaled within. The color space should be a linear space for best results. If undefined,srgb-linearwill be used.out_spaceNoneColor space that the new color should be in. If None, the return color will be in the same color space as specified byspaceorxyz-d65ifspaceisNone.methodNoneA string specifying the algorithm to use. By default robertson-1968is used.**kwargsAny plugin specific parameters to pass to the blackbodymethod. - Return
- Returns a reference to the current
Color.
Color.cct
def cct(
self,
*,
method: str | None = None,
**kwargs: Any
) -> Vector:
...
- Description
- Returns the associated CCT and ∆uv for a given color. If the color is beyond an acceptable range for the algorithm or the color is very far from the locus, the result may be surprising.
- Parameters
-
Parameters Defaults Description methodNoneA string specifying the algorithm to use. By default robertson-1968is used.**kwargsAny plugin specific parameters to pass to the blackbodymethod. - Return
- Returns a list containing the correlated color temperature in Kelvin and the ∆uv.
Color.chromatic_adaptation
@classmethod
def chromatic_adaptation(
cls,
w1: tuple[float, float],
w2: tuple[float, float],
xyz: VectorLike,
*,
method: str | None = None
) -> Vector:
...
- Description
- A class method that converts an XYZ set of coordinates between two given white points. The first white point must match the white point of the current coordinates and the second white point must be the desired white point to use.
methoddictates the method of chromatic adaptation to use. - Parameters
-
Parameters Defaults Description w1Current white point of the XYZ coordinates. w2Desired white point of the XYZ coordinates. xyzThe XYZ coordinates to adapt. methodNoneThe method of chromatic adaptation to use. If not specified, the current class's default method will be used. - Return
- Returns a set of XYZ coordinates that have been chromatically adapted to the desired white point.
Color.xy
def xy(
self,
*,
white: VectorLike | None = None
) -> Vector:
...
- Description
- Retrieves the CIE 1931 (x, y) chromaticity coordinates for a given color.
- Parameters
-
Parameters Defaults Description whiteNoneSpecify the white in which to chromatically adapt the points from, if none is specified, the current color's white point is assumed. - Return
- Returns a tuple of CIE 1931 (x, y) chromaticity points for the given color. The XYZ translation to xy will use the current color's white point to ensure the values are relative to the proper white point.
Color.uv
def uv(
self,
mode: str = '1976',
*,
white: VectorLike | None = None
) -> Vector:
...
- Description
- Retrieves the UCS 1960 (u, v) chromaticity coordinates for a given color or the CIE 1976 UCS (u', v') chromaticity coordinates, the latter being the default.
- Parameters
-
Parameters Defaults Description mode'1976'A string indicating what mode to use. 1976refers to the (u', v') points as described by CIE 1976 UCS and1960describes the (u, v) points as documented by CIE 1960 UCS.whiteNoneSpecify the white in which to chromatically adapt the points from, if none is specified, the current color's white point is assumed. - Return
- Returns a tuple of (u, v) – either 1976 (u', v') or 1960 (u, v) – chromaticity points for the given color. The XYZ translation to uv will use the current color's white point to ensure the values are relative to the proper white point.
Color.get_chromaticity
def get_chromaticity(
self,
cspace: str = 'uv-1976',
*,
white: VectorLike | None = None
) -> Vector:
...
- Description
- Retrieves the 1931 xy, 1960 uv, or 1976 u'v' chromaticity coordinates with the luminance (Y). Coordinates are returned in the format specified by
cspaceand will use the white point of the current color. - Parameters
-
Parameters Defaults Description cspace'uv-1976'A string indicating what chromaticity space to use. uv-1976being the default.whiteNoneSpecify the white in which to chromatically adapt the points from, if none is specified, the current color's white point is assumed. - Return
- Returns a list of chromaticity coordinates. Results will either be in [x, y, Y] for 1931 xy, [u, v, Y] for 1960 uv, or [u', v', Y] for 1976 u'v'.
Color.chromaticity
@classmethod
def chromaticity(
cls,
space: str,
coords: VectorLike,
cspace: str = 'uv-1976',
*,
scale: bool = False,
scale_space: str | None = None,
white: VectorLike | None = None
) -> Self:
...
- Description
- Returns a color that satisfies the provided chromaticity coordinates. Coordinates can be in the form 1931 xyY, 1960 uvY, or 1976 u'v'Y and can be configured via
cspace. The target space to convert to should be specified viaspace. Chromaticity coordinates should math the white space of the targeted space, but if they are not the white point of the chromaticity coordinates can be specified withwhite. - Parameters
-
Parameters Defaults Description spaceColor space to chromaticities to. coordsThe chromaticity coordinates. Values can be in either 3D form (with luminance Y). cspace'uv-1976'A string indicating what chromaticity space to use. uv-1976being the default.whiteNoneSpecify the white in which to chromatically adapt the points from, if none is specified, the targeted color's white point is assumed. scaleTrueScale the color with a linear RGB color space as defined by scale_space.scale_spaceNoneIf scaleis enabled,scale_spacedefines the RGB color space in which the returned color should be scaled within. The color space should be a linear space for best results. If undefined,srgb-linearwill be used. - Return
- Returns a reference to a new
Colorobject that satisfies the chromaticity coordinates.
Color.convert_chromaticity
@classmethod
def convert_chromaticity(
cls,
cspace1: str,
cspace2: str,
coords: VectorLike
) -> Vector:
...
- Description
- Converts a 2D chromaticity pair from one chromaticity space to another. Supported spaces are
xy-1931,uv-1960, anduv-1976. - Parameters
-
Parameters Defaults Description cspace1Initial chromaticity space for the given coordinates. cspace2Target chromaticity space for the given coordinates. coordsThe 2D chromaticity coordinates to convert. - Return
- Returns the converted 2D chromaticity coordinates.