Skip to content

Color

SUMMARY

A color in RGBA format.

python
from telekinesis import datatypes
color = datatypes.Color([255, 128, 0])
API Reference
Complete API documentation for Color, including parameters, attributes, and methods.
View Reference →

Parameters

ParameterTypeDefaultDescription
datanp.ndarray | list | tupleRequiredRGB [R, G, B] or RGBA [R, G, B, A] channel values in the range [0, 255]. RGB input receives an alpha value of 255.

Raises

ExceptionCondition
TypeErrordata isn't array-like convertible to float32
ValueErrordata isn't length 3 or 4 after conversion; contains a non-finite value (NaN/Inf, per BaseTensor); or any channel is outside [0, 255]

Attributes

AttributeTypeDescription
datanp.ndarrayDefensive copy, shape (4,) float32, channels in [0, 255]. Assigning re-validates the same way as construction.
shapetuple[int, ...]Always (4,).
ndimintAlways 1.
dtypenp.dtypeAlways float32.
sizeintAlways 4.

Methods

MethodTypeDescription
Color.coerce(value)ColorConverts array-like data into a Color. Accepts a np.ndarray, list, or tuple. If value is already a Color, it is returned unchanged; otherwise it goes through the same checks as constructing one directly.
Color.from_hex(hex_str)ColorBuilds a Color from a hex string, with or without a leading #. A 6-digit string (RRGGBB) is treated as fully opaque (alpha defaults to 255); an 8-digit string (RRGGBBAA) sets alpha explicitly. Only 6- or 8-digit hex strings are accepted.
as_rgb()np.ndarrayReturns just the RGB channels as a copy, with alpha dropped.
to_numpy(copy=True)np.ndarrayReturns the color's channel values. With the default copy=True you get an independent copy; pass copy=False for a direct reference to the internal array instead.
to_hex()strReturns the color as an 8-digit hex string ("#RRGGBBAA"), rounding each channel to the nearest integer.
copy()ColorReturns a new, independent Color with the same data.

Operators

OperationBehavior
c == otherInherited from BaseTensor: True only if other is exactly type Color (not just any BaseTensor) with element-equal data. False/NotImplemented otherwise.
len(c)Always 4.
np.asarray(c)Returns a copy of data as an np.ndarray, with values in [0, 255] (not normalized); NumPy functions accept a Color directly. Passing copy=False raises ValueError.
repr(c)Overridden to "Color(#RRGGBBAA)" (equivalent to to_hex()), instead of BaseTensor's default array dump.

Visualization

python
import rerun as rr

# Your code block
# ....

rr.init("color_example", spawn=True)
datatypes.visualize(color, entity_path="/color", label="Color")

Example

python
"""Demonstrates the Telekinesis Color datatype."""

import time

import numpy as np
import rerun as rr
from loguru import logger

from telekinesis import datatypes

def color_example():
    """Demonstrate creation, inspection, operations, visualization, and serialization."""

    # ======================= Create ============================================
    rgb = [255, 0, 128]
    color = datatypes.Color(rgb)
    logger.info(f"Created Color: {color}")

    hex_color = "#FF00FF80"
    color_from_hex = datatypes.Color.from_hex(hex_color)
    logger.info(f"Color created from hex {hex_color}: {color_from_hex}")

    # ======================= Inspect ===========================================
    logger.info(f"data={color.data}")
    logger.info(f"shape={color.shape}")
    logger.info(f"ndim={color.ndim}")
    logger.info(f"dtype={color.dtype}")
    logger.info(f"size={color.size}")

    # ======================= Operations =========================================
    color.data = [0, 255, 255, 255]
    logger.info(f"Updated Color: {color}")

    color_copy = color.copy()
    logger.info(f"Copied Color: {color_copy}")

    color_numpy = color.to_numpy(copy=True)
    logger.info(f"NumPy Color: {color_numpy}")

    numpy_array = np.asarray(color)
    logger.info(f"NumPy array via __array__: {numpy_array}")

    hex_str = color.to_hex()
    logger.info(f"Color converted to hex: {hex_str}")
    logger.info(f"Hex round-trip successful: {datatypes.Color.from_hex(hex_str) == color}")

    # ======================= Visualize =========================================
    rr.init("color_example", spawn=True)
    datatypes.visualize(color, entity_path="/color/updated")
    datatypes.visualize(color_copy, entity_path="/color/copy")
    datatypes.visualize(color_from_hex, entity_path="/color/from_hex")

    # ======================= Serialize / Deserialize ===========================
    start = time.perf_counter()
    serialized = datatypes.serialize(color)
    serialization_ms = (time.perf_counter() - start) * 1000

    start = time.perf_counter()
    deserialized = datatypes.deserialize(serialized)["param_0"]
    deserialization_ms = (time.perf_counter() - start) * 1000

    logger.info(f"Deserialized Color: {deserialized}")
    logger.info(f"Round-trip successful: {color == deserialized}")
    logger.info(f"Serialization time: {serialization_ms:.3f} ms")
    logger.info(f"Deserialization time: {deserialization_ms:.3f} ms")


if __name__ == "__main__":
    color_example()