Esempio n. 1
0
def main():
    """ Main function. """

    try:
        cv = Canvas(8, 2)
    except CanvasError as err:
        sys.stderr.write("%s\n" % err)
        sys.exit(127)

    cv.set_color_ansi(caca.COLOR_WHITE, caca.COLOR_BLACK)
    cv.put_str(0, 0, "ABcde")
    cv.set_color_ansi(caca.COLOR_LIGHTRED, caca.COLOR_BLACK)
    cv.put_str(5, 0, "\\o/")
    cv.set_color_ansi(caca.COLOR_WHITE, caca.COLOR_BLUE)
    cv.put_str(0, 1, "&$âøÿØ?!")

    fonts = caca.get_font_list()
    if not fonts:
        sys.stderr.write("libcaca was compiled without any fonts\n")
        sys.exit(127)

    try:
        f = Font(fonts[0])
    except FontError as err:
        sys.stderr.write("%s\n" % err)
        sys.exit(127)

    w = cv.get_width() * f.get_width()
    h = cv.get_height() * f.get_height()
    buf = ctypes.c_buffer(4 * w * h)

    cv.render(f, buf, w, h, 4 * w)

    cv.set_size(80, 32)
    try:
        dp = Display(cv)
    except DisplayError as err:
        sys.stderr.write("%s\n" % err)
        sys.exit(127)

    try:
        if sys.byteorder == 'big':
            dit = Dither(32, w, h, 4 * w, 0xff0000, 0xff00, 0xff, 0xff000000)
        else:
            dit = Dither(32, w, h, 4 * w, 0xff00, 0xff0000, 0xff000000, 0xff)

        dit.bitmap(cv, 0, 0, cv.get_width(), cv.get_height(), buf)
    except DitherError as err:
        sys.stderr.write("%s\n" % err)
        sys.exit(127)
    else:
        dp.refresh()

    dp.get_event(caca.EVENT_KEY_PRESS, Event(), -1)
Esempio n. 2
0
    def __init__(self, settings):
        red, green, blue, alpha = settings.masks
        self.dit = Dither(settings.bpp, settings.img_size[0],
                          settings.img_size[1],
                          settings.depth * settings.img_size[0], red, green,
                          blue, alpha)
        self.dit.set_algorithm(settings.dither.encode('ascii'))
        self.dit.set_charset(b"utf8")

        self.canvas = Canvas(settings.text_size[0], settings.text_size[1])
        self.canvas.set_color_ansi(caca.COLOR_DEFAULT, caca.COLOR_TRANSPARENT)

        self.settings = settings
        self._buffer = bytearray([0] * (bpc * self.settings.total_chars))

        caca_lib.caca_get_canvas_attrs.argtypes = [caca.canvas._Canvas]
        caca_lib.caca_get_canvas_attrs.restype = ctypes.POINTER(
            ctypes.c_uint32 * settings.total_chars)
        caca_lib.caca_get_canvas_chars.argtypes = [caca.canvas._Canvas]
        caca_lib.caca_get_canvas_chars.restype = ctypes.POINTER(
            (ctypes.c_uint8 * 4) * settings.total_chars)
Esempio n. 3
0
def main():
    """ Main function. """

    try:
        cv = Canvas(8, 2)
    except CanvasError as err:
        sys.stderr.write("%s\n" % err)
        sys.exit(127)

    cv.set_color_ansi(caca.COLOR_WHITE, caca.COLOR_BLACK)
    cv.put_str(0, 0, "ABcde")
    cv.set_color_ansi(caca.COLOR_LIGHTRED, caca.COLOR_BLACK)
    cv.put_str(5, 0, "\\o/")
    cv.set_color_ansi(caca.COLOR_WHITE, caca.COLOR_BLUE)
    cv.put_str(0, 1, "&$âøÿØ?!")

    fonts = caca.get_font_list()
    if not fonts:
        sys.stderr.write("libcaca was compiled without any fonts\n")
        sys.exit(127)

    try:
        f = Font(fonts[0])
    except FontError as err:
        sys.stderr.write("%s\n" % err)
        sys.exit(127)

    w = cv.get_width() * f.get_width()
    h = cv.get_height() * f.get_height()
    buf = ctypes.c_buffer(4 * w * h)

    cv.render(f, buf, w, h, 4 * w)

    cv.set_size(80, 32)
    try:
        dp = Display(cv)
    except DisplayError as err:
        sys.stderr.write("%s\n" % err)
        sys.exit(127)

    try:
        if sys.byteorder == 'big':
            dit = Dither(32, w, h, 4 * w, 0xff0000, 0xff00, 0xff, 0xff000000)
        else:
            dit = Dither(32, w, h, 4 * w, 0xff00, 0xff0000, 0xff000000, 0xff)

        dit.bitmap(cv, 0, 0, cv.get_width(), cv.get_height(), buf)
    except DitherError as err:
        sys.stderr.write("%s\n" % err)
        sys.exit(127)
    else:
        dp.refresh()

    dp.get_event(caca.EVENT_KEY_PRESS, Event(), -1)
Esempio n. 4
0
class State:
    def __init__(self, settings):
        red, green, blue, alpha = settings.masks
        self.dit = Dither(settings.bpp, settings.img_size[0],
                          settings.img_size[1],
                          settings.depth * settings.img_size[0], red, green,
                          blue, alpha)
        self.dit.set_algorithm(settings.dither.encode('ascii'))
        self.dit.set_charset(b"utf8")

        self.canvas = Canvas(settings.text_size[0], settings.text_size[1])
        self.canvas.set_color_ansi(caca.COLOR_DEFAULT, caca.COLOR_TRANSPARENT)

        self.settings = settings
        self._buffer = bytearray([0] * (bpc * self.settings.total_chars))

        caca_lib.caca_get_canvas_attrs.argtypes = [caca.canvas._Canvas]
        caca_lib.caca_get_canvas_attrs.restype = ctypes.POINTER(
            ctypes.c_uint32 * settings.total_chars)
        caca_lib.caca_get_canvas_chars.argtypes = [caca.canvas._Canvas]
        caca_lib.caca_get_canvas_chars.restype = ctypes.POINTER(
            (ctypes.c_uint8 * 4) * settings.total_chars)

    def add_frame(self, path, display=False):
        img = Image.open(path)
        if img.mode != self.settings.im_mode:
            img = img.convert(self.settings.im_mode)
        assert img.size == self.settings.img_size

        self.dit.bitmap(self.canvas, 0, 0, self.settings.text_size[0],
                        self.settings.text_size[1], img.tobytes())
        if display:
            stderr.write("%s" % self.canvas.export_to_memory("utf8"))

        offset = 0
        attrs = caca_lib.caca_get_canvas_attrs(self.canvas).contents
        chars = caca_lib.caca_get_canvas_chars(self.canvas).contents
        for i in range(self.settings.total_chars):
            attr = attrs[i]
            char = chars[i]
            char = bytearray(char).decode('utf-32-le')
            info = load_char(attr, char)
            encoded = info.save()
            assert len(encoded) == bpc
            for b in encoded:
                self._buffer[offset] = b
                offset += 1

        self.canvas.clear()
        return self._buffer
Esempio n. 5
0
def to_ascii(
    img,
    width=60,
    height=None,
    font_width=6,
    font_height=10,
    brightness=1.0,
    contrast=1.0,
    gamma=1.0,
    ditalgo="fstein",
    exformat="ansi",
        charset="ascii"):
    """
    Takes a file-pointer to an image and converts it to ASCII.
        Options:
          -h, --help                      This help
          -v, --version                   Version of the program
          -W, --width=WIDTH               Width of resulting image
          -H, --height=HEIGHT             Height of resulting image
          -x, --font-width=WIDTH          Width of output font
          -y, --font-height=HEIGHT        Height of output font
          -b, --brightness=BRIGHTNESS     Brightness of resulting image
          -c, --contrast=CONTRAST         Contrast of resulting image
          -g, --gamma=GAMMA               Gamma of resulting image
          -d, --dither=DITHER             Dithering algorithm to use
          -f, --format=FORMAT             Format of the resulting image
          -C, --charset=CHARSET           Charset of the resulting image
        DITHER (ditalgo) list:
          - none: no dithering
          - ordered2: 2x2 ordered dithering
          - ordered4: 4x4 ordered dithering
          - ordered8: 8x8 orederd dithering
          - random: random dithering
          - fstein: Floyd-Steinberg dithering
        FORMAT (exformat) list:
          - caca: native libcaca format
          - ansi: ANSI
          - utf8: UTF-8 with ANSI escape codes
          - utf8cr: UTF-8 with ANSI escape codes and MS-DOS \\r
          - html: HTML
          - html3: backwards-compatible HTML
          - bbfr: BBCode (French)
          - irc: IRC with mIRC colours
          - ps: PostScript document
          - svg: SVG vector image
          - tga: TGA image
          - troff: troff source
        CHARSET (charset) list:
          - ascii: use only ascii character
          - shades: use unicode character
          - blocks: use unicode quarter-cell combinations
    """
    img = Image.open(img)

    if "shades" or "blocks" in charset:
        exformat = "utf8"  # Will not work in ascii mode

    # Explicitly encode argument strings as ASCII
    ditalgo = ditalgo.encode('ascii')
    exformat = exformat.encode('ascii')
    charset = charset.encode('ascii')

    # Set height to some proportion
    if height is None:
        height = round(width * img.size[1] * font_width / img.size[0] / font_height)

    # Setup the canvas
    cv = Canvas(width, height)
    cv.set_color_ansi(caca.COLOR_DEFAULT, caca.COLOR_TRANSPARENT)

    #########################
    #### Begin Dithering ####
    #########################
    RMASK = 0x00ff0000
    GMASK = 0x0000ff00
    BMASK = 0x000000ff
    AMASK = 0xff000000
    BPP = 32
    DEPTH = 4

    if img.mode == 'RGB':
        img = img.convert('RGBA')
    #reorder rgba
    if img.mode == 'RGBA':
        r, g, b, a = img.split()
        img = Image.merge("RGBA", (b, g, r, a))
    dit = Dither(BPP, img.size[0], img.size[1], DEPTH * img.size[0], RMASK, GMASK, BMASK, AMASK)

    # print(dit.get_algorithm_list());
    # import ipdb; ipdb.set_trace()
    dit.set_algorithm(ditalgo)
    dit.set_brightness(brightness)
    dit.set_gamma(gamma)
    dit.set_contrast(contrast)
    dit.set_charset(charset)
    dit.bitmap(cv, 0, 0, width, height, img.tobytes())

    #########################
    #### End Dithering ######
    #########################

    return cv.export_to_memory(exformat)
Esempio n. 6
0
    except FontError, err:
        sys.stderr.write("%s\n" % err)
        sys.exit(127)

    w = cv.get_width() * f.get_width()
    h = cv.get_height() * f.get_height()
    buf = ctypes.c_buffer(4 * w * h)

    cv.render(f, buf, w, h, 4 * w)

    cv.set_size(80, 32)
    try:
        dp = Display(cv)
    except DisplayError, err:
        sys.stderr.write("%s\n" % err)
        sys.exit(127)

    if sys.byteorder == 'big':
        dit = Dither(32, w, h, 4 * w, 0xff0000, 0xff00, 0xff, 0xff000000)
    else:
        dit = Dither(32, w, h, 4 * w, 0xff00, 0xff0000, 0xff000000, 0xff)

    dit.bitmap(cv, 0, 0, cv.get_width(), cv.get_height(), buf)
    dp.refresh()

    dp.get_event(caca.EVENT_KEY_PRESS, Event(), -1)

if __name__ == "__main__":
    main()

Esempio n. 7
0
        sys.stderr.write("%s\n" % err)
        sys.exit(127)

    cv.set_color_ansi(caca.COLOR_DEFAULT, caca.COLOR_TRANSPARENT)

    #init dither
    try:
        #convert rgb to rgba
        if img.mode == 'RGB':
            img = img.convert('RGBA')
        #reorder rgba
        if img.mode == 'RGBA':
            r, g, b, a = img.split()
            img = Image.merge("RGBA", (b, g, r, a))

        dit = Dither(BPP, img.size[0], img.size[1], DEPTH * img.size[0],
                        RMASK, GMASK, BMASK, AMASK)
    except DitherError, err:
        sys.stderr.write("%s\n" % err)
        sys.exit(127)

    #set dither algorithm
    if ditalgo:
        dit.set_algorithm(ditalgo)

    #set brightness
    if brightness:
        dit.set_brightness(brightness)

    #set gamma
    if gamma:
        dit.set_gamma(gamma)
def asciiart(img, SC, GCF):
    img = cv2.convertScaleAbs(img, alpha=GCF, beta=0)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    img = Image.fromarray(img)

    RMASK = 0x00ff0000
    GMASK = 0x0000ff00
    BMASK = 0x000000ff
    AMASK = 0xff000000
    BPP = 32
    DEPTH = 4

    brightness = None
    contrast = None
    gamma = None
    ditalgo = None
    exformat = "svg"
    charset = None

    width = int(img.size[1] * 2.23 * SC)
    height = int(img.size[0] * 0.75 * SC)

    cv = Canvas(width, height)
    cv.set_color_ansi(caca.COLOR_DEFAULT, caca.COLOR_TRANSPARENT)

    try:
        # convert rgb to rgba
        if img.mode == 'RGB':
            img = img.convert('RGBA')
        # reorder rgba
        if img.mode == 'RGBA':
            r, g, b, a = img.split()
            img = Image.merge("RGBA", (b, g, r, a))
        dit = Dither(BPP, img.size[0], img.size[1], DEPTH * img.size[0], RMASK,
                     GMASK, BMASK, AMASK)
    except DitherError as err:
        print(err)

    if ditalgo:
        dit.set_algorithm(ditalgo)

    # set brightness
    if brightness:
        dit.set_brightness(brightness)

    # set gamma
    if gamma:
        dit.set_gamma(gamma)

    # set contrast
    if contrast:
        dit.set_contrast(contrast)

    # set charset
    if charset:
        dit.set_charset(charset)

    #create dither
    dit.bitmap(cv, 0, 0, width, height, img.tobytes())

    asciiArt = cv.export_to_memory(exformat)

    ##############################################################

    bgcolor = 'white'

    font = ImageFont.truetype("DejaVuSansMono.ttf", 11)

    #letter_width = font.getsize("X")[0]
    letter_height = font.getsize("X")[1]

    lines = asciiArt.split('\n')

    canvasHeight = int(lines[1].split('"')[3])
    canvasWidth = int(lines[1].split('"')[1])

    newImg = Image.new("RGB", (canvasWidth, canvasHeight), bgcolor)
    draw = ImageDraw.Draw(newImg)

    for char in lines[3:-3]:
        type = char.split('"')[0].split(" ")[0][1:]

        x = int(char.split('"')[3])
        y = int(char.split('"')[5])
        color = char.split('"')[1].split(":")[1]
        if type == "text":
            character = str(char.split('"')[-1][1:2])
            draw.text((x, y - letter_height), character, color, font=font)
        else:
            rectWidth = int(char.split('"')[-4])
            rectheight = int(char.split('"')[-2])
            draw.rectangle(((x, y), (x + rectWidth, y + rectheight)),
                           fill=color)

    finalImg = np.asarray(newImg)
    finalImg = cv2.cvtColor(finalImg, cv2.COLOR_BGR2RGB)
    return finalImg