Skip to content

image

chromatic.image

ansi2img(arr, /, font=uf.VGA437, font_size=16, *, fg_default=(170, 170, 170), bg_default=(0, 0, 0))

Render an ANSI array as an image.

Parameters:

Name Type Description Default
arr color_chain or 2D array-like

2D ANSI string array.

required
font FontArgType

Font to render the ANSI strings with.

VGA437
font_size int

Font size in pixels.

16
fg_default tuple[int, int, int] | tuple[int, int, int, int]

Default foreground color of rendered text.

(170, 170, 170)
bg_default tuple[int, int, int] | tuple[int, int, int, int]

Default background color of rendered text, and the fill color of the base canvas.

(0, 0, 0)

Returns:

Name Type Description
ansi_img Image

The rendered ANSI array as an Image.Image object.

Raises:

Type Description
ValueError

If the input ANSI array is empty.

See Also

img2ansi : Create an ANSI array from an input image, font, and character set.

Source code in chromatic/image/_array.py
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
@rgb_dispatch("fg_default", "bg_default")
def ansi2img(
    arr: (
        _tp.ShapedNDArray[tuple[int, int], np.void]
        | core.color_chain
        | list[list[core.ColorStr]]
    ),
    /,
    font: _tp.FontArgType = uf.VGA437,
    font_size=16,
    *,
    fg_default: _tp.Int3Tuple | _tp.TupleOf4[int] | str = (170, 170, 170),
    bg_default: _tp.Int3Tuple | _tp.TupleOf4[int] | str = (0, 0, 0),
):
    """Render an ANSI array as an image.

    Parameters
    ----------
    arr : color_chain or 2D array-like
        2D ANSI string array.

    font : FontArgType
        Font to render the ANSI strings with.

    font_size : int
        Font size in pixels.

    fg_default : tuple[int, int, int] | tuple[int, int, int, int]
        Default foreground color of rendered text.

    bg_default : tuple[int, int, int] | tuple[int, int, int, int]
        Default background color of rendered text, and the fill color of the base canvas.

    Returns
    -------
    ansi_img : Image
        The rendered ANSI array as an `Image.Image` object.

    Raises
    ------
    ValueError
        If the input ANSI array is empty.

    See Also
    --------
    img2ansi : Create an ANSI array from an input image, font, and character set.
    """
    if isinstance(arr, core.color_chain):
        arr = arr.term_array()
    elif not isinstance(arr, np.ndarray):
        arr = np.asarray(
            [core.color_chain(x) for x in arr], dtype=core.color_chain.dtype
        )
    if not arr.size:
        raise ValueError("input array is empty")

    font = ImageFont.truetype(get_font_object(font, retpath=True), font_size)
    bbox_h = _get_bbox_shape(font)[-1]
    widths = np.asarray(
        [[font.getbbox(c)[2] for c in x["char"]] for x in arr], dtype=np.uint32
    )

    iw = widths.sum(axis=1).max().item()
    ih = round(arr.shape[0] * bbox_h)

    channels = [fg_default, bg_default]
    rgba = False

    for c in channels:
        x = len(c)
        if x == 4:
            rgba = True
        elif x != 3:
            raise ValueError
    if rgba:
        mode = "RGBA"
        rgba_descr = arr.dtype.descr.copy()
        *rgb_args, (subd1, subd2) = rgba_descr[-1]
        rgba_descr[-1] = (*rgb_args, (subd1, subd2 + 1))
        arr = arr.astype(rgba_descr)
        arr["rgb"][..., 0, -1] = 0xFF
    else:
        mode = "RGB"

    for i, fill in enumerate(channels):
        mask = arr["rgb"][..., i, 0] == 0
        arr["rgb"][mask, i, 0] = 1
        arr["rgb"][mask, i, 1 : len(fill) + 1] = fill

    img = Image.new(mode, (iw, ih), bg_default)
    draw = ImageDraw.Draw(img)
    y_offset = 0
    for y in range(arr.shape[0]):
        x_offset = 0
        for x in range(arr.shape[1]):
            width = widths[y, x]
            item = arr[y, x]
            fg, bg = (tuple(ch) if ans else None for [ans, *ch] in item["rgb"].tolist())
            if bg is not None:
                draw.rectangle(
                    (x_offset, y_offset, x_offset + width, y_offset + bbox_h), fill=bg
                )
            draw.text((x_offset, y_offset), item["char"], font=font, fill=fg)
            x_offset += width
        y_offset += bbox_h
    return img

ansi_quantize(img, ansi_type)

Color-quantize an RGB array into ANSI 4-bit or 8-bit color space.

Parameters:

Name Type Description Default
img RGBArray

Input image in RGB format.

required
ansi_type type[ansicolor4Bit | ansicolor8Bit]

ANSI color format to map the quantized image to.

required

Raises:

Type Description
TypeError

If ansi_type is not ansi_color_4Bit or ansi_color_8Bit.

Returns:

Name Type Description
quantized RGBArray

The image with RGB values transformed into ANSI color space.

Source code in chromatic/image/_array.py
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
def ansi_quantize(img: _tp.RGBArray, ansi_type: core.AnsiColorParam):
    """Color-quantize an RGB array into ANSI 4-bit or 8-bit color space.

    Parameters
    ----------
    img : RGBArray
        Input image in RGB format.

    ansi_type : type[ansicolor4Bit | ansicolor8Bit]
        ANSI color format to map the quantized image to.

    Raises
    ------
    TypeError
        If `ansi_type` is not ``ansi_color_4Bit`` or ``ansi_color_8Bit``.

    Returns
    -------
    quantized : RGBArray
        The image with RGB values transformed into ANSI color space.
    """
    ansi_type = core.get_ansi_type(ansi_type)
    if ansi_type is core.ansicolor4Bit:
        img = nearest_ansi_4bit_rgb(img)
    elif ansi_type is core.ansicolor8Bit:
        img = nearest_ansi_8bit_rgb(img)
    return img

ansify(img, /, font=uf.VGA437, font_size=16, *, factor=200, char_set=None, sort_glyphs=True, ansi_type=None, equalize=False, fg=(170, 170, 170), bg=(0, 0, 0))

Source code in chromatic/image/_array.py
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
def ansify(
    img: str | os.PathLike[str] | _tp.RGBImageLike,
    /,
    font: _tp.FontArgType = uf.VGA437,
    font_size: int = 16,
    *,
    factor: int = 200,
    char_set: tp.Optional[str] = None,
    sort_glyphs: bool | tp.Literal[-1] = True,
    ansi_type: tp.Optional[core.AnsiColorParam] = None,
    equalize: bool | tp.Literal["white_point"] = False,
    fg: _tp.Int3Tuple | str = (170, 170, 170),
    bg: _tp.Int3Tuple | str = (0, 0, 0),
):
    arr = img2ansi(
        img,
        font,
        factor=factor,
        char_set=char_set,
        ansi_type=ansi_type,
        sort_glyphs=sort_glyphs,
        equalize=equalize,
        bg=bg,
        outarray=True,
    )
    if arr.ndim == 4:
        arr = arr[0]
    assert _is_cc_array2d(arr)
    return ansi2img(arr, font, font_size=font_size, fg_default=fg, bg_default=bg)

ascii2img(s, /, font=uf.VGA437, font_size=16, *, fg=(0, 0, 0), bg=(255, 255, 255))

Render a literal string as an image.

Parameters:

Name Type Description Default
s str

The ASCII string to convert into an image.

required
font FontArgType

Font to use for rendering the ASCII characters.

VGA437
font_size int

Font size in pixels for the rendered ASCII characters.

16
fg tuple[int, int, int]

Foreground (text) color.

(0, 0, 0)
bg tuple[int, int, int]

Background color.

(255, 255, 255)

Returns:

Name Type Description
ascii_img Image

A Image.Image object of the rendered ASCII string.

See Also

img2ascii : Convert an image into an ASCII string.

Source code in chromatic/image/_array.py
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
@rgb_dispatch("fg", "bg")
def ascii2img(
    s: str,
    /,
    font: _tp.FontArgType = uf.VGA437,
    font_size=16,
    *,
    fg: _tp.Int3Tuple | str = (0, 0, 0),
    bg: _tp.Int3Tuple | str = (0xFF, 0xFF, 0xFF),
):
    """Render a literal string as an image.

    Parameters
    ----------
    s : str
        The ASCII string to convert into an image.

    font : FontArgType
        Font to use for rendering the ASCII characters.

    font_size : int
        Font size in pixels for the rendered ASCII characters.

    fg : tuple[int, int, int]
        Foreground (text) color.

    bg : tuple[int, int, int]
        Background color.

    Returns
    -------
    ascii_img : Image
        A `Image.Image` object of the rendered ASCII string.

    See Also
    --------
    img2ascii : Convert an image into an ASCII string.
    """
    font = ImageFont.truetype(get_font_object(font, retpath=True), font_size)
    lines = s.split("\n")
    n_rows, n_cols = map(len, (lines, lines[0]))
    cw, ch = _get_bbox_shape(font)
    iw, ih = (int(i * j) for i, j in zip((cw, ch), (n_cols, n_rows)))
    r, g, b = tuple(map(int, bg))
    img = Image.new("RGB", (iw, ih), (r, g, b))
    draw = ImageDraw.Draw(img)
    y_offset = 0
    for line in lines:
        draw.text((0, y_offset), line, font=font, fill=fg)
        y_offset += ch
    return img

contrast_stretch(img, percentile=(2, 98))

Rescale the intensities of an RGB image using linear contrast stretching.

Balances contrast across both lightness and color.

Parameters:

Name Type Description Default
img RGBArray
required
percentile tuple[int, int]
(2, 98)

Returns:

Name Type Description
eq_img RGBArray
See Also

equalize_white_point

Source code in chromatic/image/_array.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def contrast_stretch(
    img: _tp.RGBArray, percentile: tuple[int, int] = (2, 98)
) -> _tp.RGBArray:
    """Rescale the intensities of an RGB image using linear contrast stretching.

    Balances contrast across both lightness and color.

    Parameters
    ----------
    img : RGBArray
    percentile : tuple[int, int], optional

    Returns
    -------
    eq_img : RGBArray

    See Also
    --------
    equalize_white_point
    """
    imin, imax = np.percentile(img, percentile)
    out_dtype = img.dtype
    if issubclass(dt := img.dtype.type, np.integer):
        info = np.iinfo(dt)
        omin, omax = info.min, info.max
    elif issubclass(dt, np.inexact):
        omin, omax = -1, 1
    elif dt is np.bool_:
        omin, omax = False, True
    else:
        omin, omax = imin, imax
    omin, omax = map(float, (omin, omax))
    if imin >= 0:
        omin = 0.0
    img = np.clip(img, imin, imax)
    if imin != imax:
        img = (img - imin) / (imax - imin)
        return (img * (omax - omin) + omin).astype(out_dtype)
    else:
        return np.clip(img, omin, omax).astype(out_dtype)

equalize_white_point(img)

Apply histogram equalization to the L-channel (lightness) in LAB color space.

Parameters:

Name Type Description Default
img RGBArray
required

Returns:

Name Type Description
eq_img RGBArray
See Also

contrast_stretch

Source code in chromatic/image/_array.py
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
def equalize_white_point(img: _tp.RGBArray) -> _tp.RGBArray:
    """Apply histogram equalization to the L-channel (lightness) in LAB color space.

    Parameters
    ----------
    img : RGBArray

    Returns
    -------
    eq_img : RGBArray

    See Also
    --------
    contrast_stretch
    """
    lab_img = cv.cvtColor(img, cv.COLOR_RGB2LAB)
    Lc, Ac, Bc = cv.split(lab_img)
    Lc_eq = cv.equalizeHist(Lc)
    lab_eq_img = cv.merge((Lc_eq, Ac, Bc))
    eq_img = cv.cvtColor(lab_eq_img, cv.COLOR_LAB2RGB)
    return eq_img

get_font_key(font)

Obtain a unique tuple pair from a FreeTypeFont object.

Parameters:

Name Type Description Default
font FreeTypeFont

The FreeTypeFont object from which to derive a key.

required

Returns:

Type Description
tuple[str, str]

A tuple containing the font family and font name.

Raises:

Type Description
ValueError

If the font key cannot be generated due to missing fields.

Source code in chromatic/image/_array.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
def get_font_key(font: ImageFont.FreeTypeFont):
    """Obtain a unique tuple pair from a FreeTypeFont object.

    Parameters
    ----------
    font : FreeTypeFont
        The FreeTypeFont object from which to derive a key.

    Returns
    -------
    tuple[str, str]
        A tuple containing the font family and font name.

    Raises
    ------
    ValueError
        If the font key cannot be generated due to missing fields.
    """
    font = get_font_object(font)
    font_key = font.getname()
    if not all(font_key):
        missing = []
        s = "font %s"
        if font_key[0] is None:
            missing.append(f"{s % 'name'!r}")
        if font_key[-1] is None:
            missing.append(f"{s % 'family'!r}")
        raise ValueError(
            f"Unable to generate font key due to missing fields {' and '.join(missing)}: "
            f"{font_key}"
        )
    return font_key

get_font_object(font, *, retpath=False) cached

get_font_object(font: _tp.FontArgType, *, retpath: tp.Literal[False] = False) -> ImageFont.FreeTypeFont
get_font_object(font: _tp.FontArgType, *, retpath: tp.Literal[True]) -> str
get_font_object(font: _tp.FontArgType, *, retpath: bool) -> ImageFont.FreeTypeFont | str

Return a FreeTypeFont object or its filepath.

The result is cached to prevent FreeType from consuming excessive resources.

Parameters:

Name Type Description Default
font FontArgType

FreeTypeFont, UserFont, or string.

required
retpath bool

Return filepath instead of FreeTypeFont object

False

Returns:

Type Description
FreeTypeFont or str

FreeTypeFont object, or filepath (if retpath=True).

Raises:

Type Description
TypeError

If the input type is unsupported.

Source code in chromatic/image/_array.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
@lru_cache
def get_font_object(
    font: _tp.FontArgType, *, retpath: bool = False
) -> ImageFont.FreeTypeFont | str:
    """Return a FreeTypeFont object or its filepath.

    The result is cached to prevent FreeType from consuming excessive resources.

    Parameters
    ----------
    font : FontArgType
        FreeTypeFont, UserFont, or string.

    retpath : bool, optional
        Return filepath instead of FreeTypeFont object

    Returns
    -------
    FreeTypeFont or str
        FreeTypeFont object, or filepath (if `retpath=True`).

    Raises
    ------
    TypeError
        If the input type is unsupported.
    """

    if retpath:
        return (
            getattr(font.path, "name", os.fspath(font.path))
            if isinstance(font, ImageFont.FreeTypeFont)
            else get_font_object(get_font_object(font), retpath=True)
        )
    else:
        match font:
            case ImageFont.FreeTypeFont():
                return font
            case uf.UserFont():
                return font.to_truetype()
            case str() if font in uf.userfonts:
                return get_font_object(uf.userfonts[font])
            case str() | os.PathLike():
                return ImageFont.truetype(font, 24)
    raise TypeError(
        f"Expected {ImageFont.FreeTypeFont.__name__!r} or pathlike object, "
        f"got {type(font).__name__!r} object instead"
    )

img2ansi(img, /, font=uf.VGA437, factor=200, char_set=None, sort_glyphs=True, ansi_type=None, equalize=False, bg=None, *, outarray=False)

img2ansi(img: str | os.PathLike[str] | _tp.RGBImageLike, /, font: _tp.FontArgType = ..., factor: int = ..., char_set: tp.Optional[str] = ..., sort_glyphs: bool | tp.Literal[-1] = ..., ansi_type: tp.Optional[core.AnsiColorParam] = ..., equalize: bool | tp.Literal['white_point'] = ..., bg: tp.Optional[_tp.Int3Tuple | str] = ..., *, outarray: tp.Literal[False] = False) -> core.color_chain | list[core.color_chain]
img2ansi(img: _tp.RGBArray, /, font: _tp.FontArgType = ..., factor: int = ..., char_set: tp.Optional[str] = ..., sort_glyphs: bool | tp.Literal[-1] = ..., ansi_type: tp.Optional[core.AnsiColorParam] = ..., equalize: bool | tp.Literal['white_point'] = ..., bg: tp.Optional[_tp.Int3Tuple | str] = ..., *, outarray: tp.Literal[True]) -> _tp.ShapedNDArray[tuple[int, int], np.void]
img2ansi(img: _tp.RGBArray3d, /, font: _tp.FontArgType = ..., factor: int = ..., char_set: tp.Optional[str] = ..., sort_glyphs: bool | tp.Literal[-1] = ..., ansi_type: tp.Optional[core.AnsiColorParam] = ..., equalize: bool | tp.Literal['white_point'] = ..., bg: tp.Optional[_tp.Int3Tuple | str] = ..., *, outarray: tp.Literal[True]) -> _tp.ShapedNDArray[tuple[int, int, int], np.void]
img2ansi(img: str | os.PathLike[str] | Image.Image, /, font: _tp.FontArgType = ..., factor: int = ..., char_set: tp.Optional[str] = ..., sort_glyphs: bool | tp.Literal[-1] = ..., ansi_type: tp.Optional[core.AnsiColorParam] = ..., equalize: bool | tp.Literal['white_point'] = ..., bg: tp.Optional[_tp.Int3Tuple | str] = ..., *, outarray: tp.Literal[True]) -> tp.Union[_tp.ShapedNDArray[tuple[int, int], np.void], _tp.ShapedNDArray[tuple[int, int, int], np.void]]

Convert an image to an ANSI array.

Parameters:

Name Type Description Default
img str | PathLike[str] | RGBImageLike

Base image or path to image being convert into ANSI.

required
font FontArgType

Font to use for glyph comparisons and representation.

VGA437
factor int

Length of each line in characters per line in output_str. Affects level of detail.

200
char_set str

The literal string or sequence of strings to use for greyscale interpolation and visualization.

If None (default), the character set will be determined based on the 'font' parameter.

None
sort_glyphs (True, False, -1)

Specifies to sort char_set or leave it unsorted before mapping to greyscale.

Glyph bitmasks obtained from 'font' are compared when sorting the string.

-1 specifies reverse sorting order.

True
ansi_type AnsiColorParam

ANSI color format to map the RGB values to.

Can be 4-bit, 8-bit, or 24-bit ANSI color space.

If 4-bit or 8-bit, the RGB array will be color-quantized into ANSI color space;

if 24-bit, uses the RGB colors of the image;

if None (default), uses default ANSI type (4-bit or 8-bit, depending on the system).

None
equalize (True, False, white_point)

Apply contrast equalization to the input image.

If True, performs contrast stretching;

if 'white_point', applies white-point equalization.

True
bg sequence of ints or RGBArray

Background color

None
outarray bool

If True, an ndarray is returned instead of a color_chain object.

False

Returns:

Name Type Description
ansi_array `color_chain` or ``ndarray[tuple[int, int], dtype[void]]``

The ANSI-converted image.

Raises:

Type Description
ValueError

If bg cannot be coerced into a Color object.

TypeError

If ansi_type is not a valid ANSI type.

See Also

ansi2img : Render an ANSI array as an image. img2ascii : Used to obtain the base ASCII characters.

Source code in chromatic/image/_array.py
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
@rgb_dispatch("bg")
def img2ansi(  # type: ignore
    img,
    /,
    font=uf.VGA437,
    factor=200,
    char_set=None,
    sort_glyphs=True,
    ansi_type=None,
    equalize=False,
    bg=None,
    *,
    outarray=False,
):
    """Convert an image to an ANSI array.

    Parameters
    ----------
    img : str | os.PathLike[str] | RGBImageLike
        Base image or path to image being convert into ANSI.

    font : FontArgType
        Font to use for glyph comparisons and representation.

    factor : int
        Length of each line in characters per line in `output_str`. Affects level of detail.

    char_set : str, optional
        The literal string or sequence of strings to use for greyscale interpolation and
        visualization.

        If None (default), the character set will be determined based on the 'font' parameter.

    sort_glyphs : {True, False, -1}
        Specifies to sort `char_set` or leave it unsorted before mapping to greyscale.

        Glyph bitmasks obtained from 'font' are compared when sorting the string.

        `-1` specifies reverse sorting order.

    ansi_type : AnsiColorParam
        ANSI color format to map the RGB values to.

        Can be 4-bit, 8-bit, or 24-bit ANSI color space.

        If 4-bit or 8-bit, the RGB array will be color-quantized into ANSI color space;

        if 24-bit, uses the RGB colors of the image;

        if `None` (default), uses default ANSI type (4-bit or 8-bit, depending on the system).

    equalize : {True, False, 'white_point'}
        Apply contrast equalization to the input image.

        If True, performs contrast stretching;

        if 'white_point', applies white-point equalization.

    bg : sequence of ints or RGBArray
        Background color

    outarray : bool, default=False
        If True, an ndarray is returned instead of a color_chain object.

    Returns
    -------
    ansi_array : `color_chain` or ``ndarray[tuple[int, int], dtype[void]]``
        The ANSI-converted image.

    Raises
    ------
    ValueError
        If `bg` cannot be coerced into a ``Color`` object.

    TypeError
        If `ansi_type` is not a valid ANSI type.

    See Also
    --------
    ansi2img : Render an ANSI array as an image.
    img2ascii : Used to obtain the base ASCII characters.
    """
    with _ConversionHandler(
        font,
        factor=factor,
        char_set=char_set,
        sort_glyphs=sort_glyphs,
        ansi_type=ansi_type,
        equalize=equalize,
        bg=bg,
    ) as h:
        out = h.to_ansi(img)
    if outarray is True:
        return out
    elif out.ndim == 2:
        return core.color_chain.fromarray(out)
    else:
        return [core.color_chain.fromarray(x) for x in out]

img2ascii(img, /, font=uf.VGA437, factor=200, char_set=None, sort_glyphs=True, *, outarray=False)

img2ascii(img: str | os.PathLike[str] | _tp.RGBImageLike, /, font: _tp.FontArgType = ..., factor: int = ..., char_set: tp.Optional[str] = ..., sort_glyphs: bool | tp.Literal[-1] = ..., *, outarray: tp.Literal[False] = False) -> str | list[str]
img2ascii(img: _tp.RGBArray, /, font: _tp.FontArgType = ..., factor: int = ..., char_set: tp.Optional[str] = ..., sort_glyphs: bool | tp.Literal[-1] = ..., *, outarray: tp.Literal[True]) -> _tp.ShapedNDArray[tuple[int, int], np.str_]
img2ascii(img: _tp.RGBArray3d, /, font: _tp.FontArgType = ..., factor: int = ..., char_set: tp.Optional[str] = ..., sort_glyphs: bool | tp.Literal[-1] = ..., *, outarray: tp.Literal[True]) -> _tp.ShapedNDArray[tuple[int, int, int], np.str_]
img2ascii(img: str | os.PathLike[str] | Image.Image, /, font: _tp.FontArgType = ..., factor: int = ..., char_set: tp.Optional[str] = ..., sort_glyphs: bool | tp.Literal[-1] = ..., *, outarray: tp.Literal[True]) -> tp.Union[_tp.ShapedNDArray[tuple[int, int], np.str_], _tp.ShapedNDArray[tuple[int, int, int], np.str_]]

Convert an image to a multiline ASCII string.

Parameters:

Name Type Description Default
img str | PathLike[str] | RGBImageLike

Base image being converted to ASCII.

required
font FontArgType

Font to use for glyph comparisons and representation.

VGA437
factor int

Length of each line in characters per line in output_str. Affects level of detail.

200
char_set Iterable[str]

Characters to be mapped to greyscale values of 'img'.

None
sort_glyphs (True, False, -1)

Specifies to sort char_set or leave it unsorted before mapping to greyscale.

Glyph bitmasks obtained from 'font' are compared when sorting the string.

-1 specifies reverse sorting order.

True
outarray bool

If True, returns the raw chararray. Otherwise, returns a string or list of strings.

False

Returns:

Name Type Description
output_str str

Characters from char_set mapped to the input image, as a multi-line string.

Raises:

Type Description
TypeError

If char_set is of an unexpected type.

See Also

ascii2img : Render an ASCII string as an image.

Source code in chromatic/image/_array.py
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
def img2ascii(  # type: ignore
    img,
    /,
    font=uf.VGA437,
    factor=200,
    char_set=None,
    sort_glyphs=True,
    *,
    outarray=False,
):
    """Convert an image to a multiline ASCII string.

    Parameters
    ----------
    img : str | os.PathLike[str] | RGBImageLike
        Base image being converted to ASCII.

    font : FontArgType
        Font to use for glyph comparisons and representation.

    factor : int
        Length of each line in characters per line in `output_str`. Affects level of detail.

    char_set : Iterable[str], optional
        Characters to be mapped to greyscale values of 'img'.

    sort_glyphs : {True, False, -1}
        Specifies to sort `char_set` or leave it unsorted before mapping to greyscale.

        Glyph bitmasks obtained from 'font' are compared when sorting the string.

        `-1` specifies reverse sorting order.

    outarray : bool, default=False
        If True, returns the raw chararray. Otherwise, returns a string or list of strings.

    Returns
    -------
    output_str : str
        Characters from `char_set` mapped to the input image, as a multi-line string.

    Raises
    ------
    TypeError
        If `char_set` is of an unexpected type.

    See Also
    --------
    ascii2img : Render an ASCII string as an image.
    """
    with _ConversionHandler(
        font, factor=factor, char_set=char_set, sort_glyphs=sort_glyphs
    ) as h:
        out = h.to_ascii(img)
    if outarray is True:
        return out
    newlines = np.zeros((*out.shape[:-1], 1), dtype="<U1")
    newlines[:-1] = "\n"
    out = np.concatenate((out, newlines), axis=-1)
    if out.ndim == 3:
        return "".join(out.flat)
    else:
        return ["".join(x.flat) for x in out]

otsu_mask(img)

Source code in chromatic/image/_array.py
1392
1393
1394
1395
1396
1397
1398
1399
def otsu_mask(
    img: _tp.MatrixLike[np.uint8] | cv.typing.MatLike | Image.Image,
) -> _tp.MatrixLike[np.uint8]:
    img = np.asarray(img, dtype=np.uint8)
    kernel = cv.getStructuringElement(cv.MORPH_RECT, (2, 2))
    img = cv.morphologyEx(img, cv.MORPH_OPEN, kernel)
    out = cv.threshold(img, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)[1]
    return out  # type: ignore[return-type]

read_ans(buf, /, fallback=None)

Source code in chromatic/image/_array.py
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
def read_ans(
    buf: tp.BinaryIO, /, fallback: tuple[int, int] | None = None
) -> tuple[str, _AnsiFileKwargs]:
    fallback = get_terminal_size() if fallback is None else get_terminal_size(fallback)
    buf.seek(-128, 2)
    if buf.read(5) == b"SAUCE":
        buf.seek(-5, 1)
        d = _parse_sauce(buf.read())
        if d["filetype"] > 2:
            raise ValueError(
                "unexpected filetype from SAUCE record "
                "(not ASCII or ANSi): {filetype}".format_map(d)
            )   # fmt: skip
        del d["id"], d["version"]
        d["date"] = time.strptime(d["date"], "%Y%m%d")
        d["columns"] = d.pop("tinfo1") or fallback.columns
        d["lines"] = d.pop("tinfo2") or fallback.lines
        del d["tinfo3"], d["tinfo4"]
        if n_comments := d["comments"]:
            buf.seek(-sum([128, n_comments * 64, 5]), 2)
            if buf.read(5) != b"COMNT":
                d["comments"] = False
            else:
                comments = []
                for _ in range(n_comments):
                    comment = buf.read(64).rstrip(b"\0 ").decode("cp437")
                    comments.append(comment)
                d["comments"] = "\n".join(comments)
        d["ansiflags"] = ANSiFlag(d.pop("tflags"))
        d["fontname"] = d.pop("tinfos") or None
        buf.seek(0)
        size = d["filesize"]
        content = buf.read(size)
    else:
        buf.seek(0)
        content = buf.read()
        d = {
            "columns": fallback.columns,
            "lines": fallback.lines,
            "ansiflags": 0,
            "fontname": None,
        }
    return content.decode("cp437").rstrip("\x1a"), d  # type: ignore[return-type]

render_ans(buf, /, fallback=None, font=None, font_size=16, *, bg_default=(0, 0, 0))

Return an image render of an ANS file.

Parameters:

Name Type Description Default
s str

Literal ANSI text.

required
fallback tuple[int, int]

(columns, lines) of the ANS file, if no SAUCE record is present.

Defaults to shutil.get_terminal_size()

None
font FontArgType

Font to draw the image. Overrides SAUCE record if present.

None
font_size int

Font size in pixels.

16
bg_default tuple[int, int, int] or tuple[int, int, int, int]

Background color to use as a fallback when ANSI SGR has none.

(0, 0, 0)
Source code in chromatic/image/_array.py
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
def render_ans(
    buf: tp.BinaryIO,
    /,
    fallback: tuple[int, int] | None = None,
    font: _tp.FontArgType | None = None,
    font_size: int = 16,
    *,
    bg_default: _tp.Int3Tuple | _tp.TupleOf4[int] | str = (0, 0, 0),
) -> Image.Image:
    """Return an image render of an ANS file.

    Parameters
    ----------
    s : str
        Literal ANSI text.

    fallback : tuple[int, int]
        ``(columns, lines)`` of the ANS file, if no SAUCE record is present.

        Defaults to ``shutil.get_terminal_size()``

    font : FontArgType
        Font to draw the image. Overrides SAUCE record if present.

    font_size : int
        Font size in pixels.

    bg_default : tuple[int, int, int] or tuple[int, int, int, int]
        Background color to use as a fallback when ANSI SGR has none.
    """
    content, d = read_ans(buf, fallback=fallback)
    if fallback is None:
        fallback = d["columns"], d["lines"]
    if font is None:
        if (fontname := d["fontname"]) and fontname in uf.userfonts:
            font = uf.userfonts[fontname]
        elif (fontname or "").startswith(("IBM VGA", "IBM EGA")):
            font = uf.VGA437
        else:
            font = uf.DEFAULT_FONT
    flags = ReshapeAnsiFlag.BOLD_COLORS
    if d["ansiflags"] & ANSiFlag.ICE_COLORS:
        flags |= ReshapeAnsiFlag.ICE_COLORS
    norm = reshape_ansi(content, fallback, flags)
    arr = [
        [core.ColorStr(f"{sgr}{s}") for sgr, s in line] for line in norm.splitlines()
    ]
    return ansi2img(arr, font, font_size, bg_default=bg_default)

render_font_char(c, /, font, size=(24, 24), fill=(255, 255, 255))

Render a one-character string as an image.

Parameters:

Name Type Description Default
c str

Character to be rendered.

required
font FontArgType

Font to use for rendering.

required
size tuple[int, int]

Size of the bounding box to use for the output image, in pixels.

(24, 24)
fill tuple[int, int, int]

The color to fill the character.

(255, 255, 255)

Returns:

Name Type Description
Image

The character rendered in the given font.

Raises:

Type Description
ValueError : If the input string is longer than a single character.
Source code in chromatic/image/_array.py
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
def render_font_char(
    c: str,
    /,
    font: _tp.FontArgType,
    size=(24, 24),
    fill: _tp.Int3Tuple = (0xFF, 0xFF, 0xFF),
):
    """Render a one-character string as an image.

    Parameters
    ----------
    c : str
        Character to be rendered.

    font : FontArgType
        Font to use for rendering.

    size : tuple[int, int]
        Size of the bounding box to use for the output image, in pixels.

    fill : tuple[int, int, int]
        The color to fill the character.

    Returns
    -------
    Image :
        The character rendered in the given font.

    Raises
    ------
        ValueError : If the input string is longer than a single character.
    """
    if len(c) > 1:
        raise ValueError(f"expected a character, but string of length {len(c)} found")
    img = Image.new("RGB", size=size)
    draw = ImageDraw.Draw(img)
    font_obj = get_font_object(font)
    bbox = draw.textbbox((0, 0), c, font=font_obj)
    x_offset, y_offset = (
        (size[i] - (bbox[i + 2] - bbox[i])) // 2 - bbox[i] for i in range(2)
    )
    draw.text((x_offset, y_offset), c, font=font_obj, fill=fill)
    return img

render_font_str(s, /, font)

Render a string as an image using the specified font.

Parameters:

Name Type Description Default
s str

The string to render.

required
font FontArgType

The font to use for rendering.

required

Returns:

Type Description
ImageType

An image of the rendered string.

Raises:

Type Description
ValueError

If the string is empty.

Source code in chromatic/image/_array.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
def render_font_str(s: str, /, font: _tp.FontArgType):
    """Render a string as an image using the specified font.

    Parameters
    ----------
    s : str
        The string to render.

    font : FontArgType
        The font to use for rendering.

    Returns
    -------
    ImageType
        An image of the rendered string.

    Raises
    ------
    ValueError
        If the string is empty.
    """
    s = s.expandtabs(4)
    font = get_font_object(font)
    if len(s) > 1:
        lines = s.splitlines()
        maxlen = max(map(len, lines))
        stacked = np.vstack(
            [
                np.hstack(
                    [
                        np.array(render_font_char(c, font=font), dtype=np.uint8)
                        for c in line
                    ]
                )
                for line in map(lambda x: f"{x:<{maxlen}}", lines)
            ]
        )
        return Image.fromarray(stacked)
    return render_font_char(s, font)

reshape_ansi(s, /, shape, flags=0)

Return the string padded for a grid with dims shape.

The output string represents a terminal render after stateful transitions have been applied.

Cursor codes and '\r' are consumed and resolved to character emplacements, and null character cells are translated to whitespace (0x20).

Parameters:

Name Type Description Default
s str
required
shape tuple[int, int]

Shape of the output as (width, height). Must be 2D.

required
flags int

Additonal flags for state transitions. See ReshapeAnsiFlag for more info.

0

Returns:

Name Type Description
out str

Reshaped string with ANSI escape state transitions applied.

Source code in chromatic/image/_array.py
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
def reshape_ansi(s: str, /, shape: tuple[int, int], flags=0) -> core.color_chain:
    """Return the string padded for a grid with dims `shape`.

    The output string represents a terminal render after stateful transitions
    have been applied.

    Cursor codes and `'\\r'` are consumed and resolved to character emplacements,
    and null character cells are translated to whitespace (0x20).

    Parameters
    ----------
    s : str

    shape : tuple[int, int]
        Shape of the output as (width, height). Must be 2D.

    flags : int, default=0
        Additonal flags for state transitions. See ``ReshapeAnsiFlag`` for more
        info.

    Returns
    -------
    out : str
        Reshaped string with ANSI escape state transitions applied.
    """
    w, h = shape
    total = w * h

    chars = np.zeros(total, dtype="<U1")
    sgr_ids = np.full(total, -1, dtype=np.intp)

    pos = y = x = 0

    def move(i: int):
        nonlocal pos, y, x
        pos = min(max(i, 0), total - 1)
        y, x = divmod(pos, w)

    cursor_code: dict[str, abc.Callable[[int], None]] = {
        "A": lambda n: move(max(0, y - n) * w + x),
        "B": lambda n: move(min(h - 1, y + n) * w + x),
        "C": lambda n: move(y * w + min(w - 1, x + n)),
        "D": lambda n: move(y * w + max(0, x - n)),
        "E": lambda n: move(min(h - 1, y + n) * w),
        "F": lambda n: move(max(0, y - n) * w),
        "G": lambda n: move(y * w + min(w - 1, max(0, n - 1))),
        "H": move,
    }
    cursor_crlf: dict[str, abc.Callable[[], None]] = {
        "\r": lambda: move(y * w),
        "\n": lambda: move(min(h - 1, y + 1) * w),
    }

    finditer = cursor_or_sgr_pattern().finditer
    update_sgr = _sgr_state_updater(flags)
    sgr_buf: list[core.SgrSequence] = [update_sgr(core.SgrSequence())]
    seen = False
    for line in s.split("\n"):
        for m in finditer(line):
            if cg := m["cursor"]:
                nums, code = cg[:-1], cg[-1]
                if code == "H":
                    y_, x_ = (max(0, int(n or 1) - 1) for n in nums.partition(";")[::2])
                    n = min(y_, h - 1) * w + min(x_, w - 1)
                else:
                    n = int(nums or 1)
                cursor_code[code](n)
            elif m["carriage_return"]:
                cursor_crlf["\r"]()
            elif sgr_s := m["sgr"]:
                sgr_buf.append(update_sgr(core.SgrSequence(sgr_s[:-1].encode())))
                seen = True
            if text := m["text"]:
                count = min(len(text), total - pos)
                span = slice(pos, pos + count)
                chars[span] = [*text[:count]]
                sgr_ids[span] = len(sgr_buf) - 1
                move(pos + count)
        cursor_crlf["\n"]()

    chars[~chars.astype(np.bool_)] = " "
    if not seen:
        return core.color_chain("\n".join(map("".join, chars.reshape(h, w))))

    # sgr state ffill
    src = np.where(sgr_ids >= 0, np.arange(total), 0)
    np.maximum.accumulate(src, out=src)
    cell_ids = sgr_ids[src]

    keys: dict[bytes, int] = {}
    i2k = np.empty(len(sgr_buf) + 1, dtype=np.intp)
    i2k[0] = -1
    for i, sgr in enumerate(sgr_buf):
        i2k[i + 1] = keys.setdefault(bytes(sgr), len(keys))
    cell_keys = i2k[cell_ids + 1]

    out = []
    prev_key = None
    was_esc = was_str = paired = False
    for r in range(h):
        lo = r * w
        r_keys = cell_keys[lo : lo + w]
        r_chars = chars[lo : lo + w]
        starts = np.flatnonzero(np.r_[True, r_keys[1:] != r_keys[:-1]])
        for i, start in enumerate(starts):
            stop = starts[i + 1] if i + 1 < starts.size else w
            key = int(r_keys[start])
            if key != prev_key and key >= 0:
                out.append(sgr_buf[int(cell_ids[lo + start])])
                was_esc = True
                paired = False
            prev_key = key
            s = "".join(r_chars[start:stop])
            if was_esc:
                out[-1] = [out[-1], s]
                was_esc = False
                paired = True
            elif paired:
                out[-1][1] += s
            elif was_str:
                out[-1] += s
            else:
                out.append(s)
            was_str = True
        if r < h - 1:
            if paired:
                out[-1][1] += "\n"
            elif was_str:
                out[-1] += "\n"
            else:
                out.append("\n")
            was_str = True
    return core.color_chain(
        x if isinstance(x, (core.SgrSequence, str)) else tuple(x) for x in out
    )

scale_saturation(img, alpha=None)

Source code in chromatic/image/_array.py
345
346
347
348
349
350
351
def scale_saturation(
    img: _tp.RGBArray, alpha: tp.Optional[float] = None
) -> _tp.RGBArray:
    img = cv.cvtColor(img, cv.COLOR_RGB2HSV)
    img[:, :, 1] = cv.convertScaleAbs(img[:, :, 1], alpha=alpha or 1.0)
    img[:] = cv.cvtColor(img, cv.COLOR_HSV2RGB)
    return img

shuffle_char_set(chars)

Flatten chars into a list and return the randomly shuffled string.

Parameters:

Name Type Description Default
chars Iterable[str]

Iterable of characters (or strings, which will be flattened).

required

Returns:

Type Description
str

Raises:

Type Description
TypeError

If chars is not iterable, or contains non-strings.

Source code in chromatic/image/_array.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def shuffle_char_set(chars: abc.Iterable[str]):
    """Flatten `chars` into a list and return the randomly shuffled string.

    Parameters
    ----------
    chars : Iterable[str]
        Iterable of characters (or strings, which will be flattened).

    Returns
    -------
    str

    Raises
    ------
    TypeError
        If `chars` is not iterable, or contains non-strings.
    """
    xs = list(c for s in chars for c in s)
    random.shuffle(xs)
    return "".join(xs)

ascii_printable()

Source code in chromatic/image/_curses.py
40
41
def ascii_printable():
    return bytes(range(32, 127)).decode("ascii")

backtrans_cp437(x, /, keys=None)

Translate cp437 graphical chars back into control chars

Source code in chromatic/image/_curses.py
26
27
28
29
30
31
32
def backtrans_cp437(x: str, /, keys: Iterable[int] | None = None) -> str:
    """Translate cp437 graphical chars back into control chars"""
    return x.translate(
        {v: k for k, v in CP437_TRANS_TABLE.items()}
        if keys is None
        else {CP437_TRANS_TABLE[k]: k for k in keys}
    )

cp437_printable()

Return a string containing all graphical characters in code page 437

Source code in chromatic/image/_curses.py
35
36
37
def cp437_printable():
    """Return a string containing all graphical characters in code page 437"""
    return translate_cp437(bytes([*range(1, 0x20), *range(0x21, 0xFF)]).decode("cp437"))

translate_cp437(x, /, ignore=())

Translate control chars (0x1-0x1F, 0x7F) into cp437 graphical chars

Source code in chromatic/image/_curses.py
20
21
22
23
def translate_cp437(x: str, /, ignore: Iterable[int] = ()) -> str:
    """Translate control chars (0x1-0x1F, 0x7F) into cp437 graphical chars"""
    keys = CP437_TRANS_TABLE.keys() - ignore
    return x.translate({k: CP437_TRANS_TABLE[k] for k in keys})

get_glyph_masks(font, /, char_set=None, *, dist_transform=False)

get_glyph_masks(font: _tp.FontArgType, /, char_set: abc.Sequence[str] | None = ...) -> dict[str, _tp.GlyphArray[np.uint8]]
get_glyph_masks(font: _tp.FontArgType, /, char_set: abc.Sequence[str] | None = ..., *, dist_transform: L[False]) -> dict[str, _tp.GlyphArray[np.uint8]]
get_glyph_masks(font: _tp.FontArgType, /, char_set: abc.Sequence[str] | None = ..., *, dist_transform: L[True]) -> dict[str, _tp.GlyphArray[np.float64]]
Source code in chromatic/image/_glyph.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def get_glyph_masks(
    font: _tp.FontArgType,
    /,
    char_set: abc.Sequence[str] | None = None,
    *,
    dist_transform: bool = False,
):
    from ._array import get_font_object, render_font_char

    char_set = char_set or ascii_printable()
    font = get_font_object(font)

    def _get_threshold(c: str, /):
        out = otsu_mask(render_font_char(c, font).convert("L"))
        if dist_transform is True:
            return distance_transform_edt(out)
        return out

    space = _get_threshold(" ")
    non_printable = _get_threshold("�")
    glyph_masks = {}
    for char in set(char_set):
        thresh = _get_threshold(char)
        if np.array_equal(thresh, non_printable):
            thresh = space
        glyph_masks[char] = thresh
    return glyph_masks

sort_glyphs(s, /, font, reverse=False)

Source code in chromatic/image/_glyph.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def sort_glyphs(s: str, /, font: _tp.FontArgType, reverse: bool = False):
    all_chars = list(s)
    mapping = {}
    for c, arr in get_glyph_masks(font, s, dist_transform=True).items():
        v = np.sum(arr)
        if v <= 0 and c != " ":
            continue
        mapping[c] = v
    return "".join(
        sorted(
            filter(mapping.__contains__, all_chars),
            key=mapping.__getitem__,
            reverse=reverse,
        )
    )

ttf_extract_codepoints(fp, /, **kwargs)

Source code in chromatic/image/_glyph.py
89
90
91
92
93
94
95
def ttf_extract_codepoints(
    fp: str | os.PathLike[str], /, **kwargs
) -> _tp.ShapedNDArray[tuple[int], np.uint32]:
    with TTFont(fp, **kwargs) as font:
        codepoints = {i for table in font["cmap"].tables for i in table.cmap}
    arr = np.array([i for i in codepoints if chr(i).isprintable()], dtype="<u4")
    return np.sort(arr)  # type: ignore[arg-type]