将字符转换为元组并返回

Convert character(s) to tuple and back

我正在尝试更改此编码器的输出:
https://github.com/akapila011/Text-to-Image/blob/master/text_to_image/encode.py
从灰度到三色方案,如下所示:Tricolor
我需要从编码器更改的主要代码行是:

img = Image.new("L", size)  # grayscale, blank black image

ind = 0

for row in range(0, size[0]):

    for col in range(0, size[1]):

        if ind < text_length:  # only change pixel value for length of text

            pixel_value = convert_char_to_int(text[ind], limit=limit)

            img.putpixel((row, col), pixel_value)

            ind += 1

        else:  # end of text, leave remaining pixel(s) black to indicate null

            break

img.save(result_path)

return result_path

我只加载 base64 文本,所以我严格使用 64 个字符。
有人告诉我,我需要将 convert_char_to_int 更改为 return 元组作为 RGB 值。但我不确定该怎么做?我是否将 int 转换为 rgb,如果是,如何转换?
我需要反转该过程,以便我也 Decode 将其恢复为文本。

看起来 PIL 是他们正在使用的库。要回答您的问题,这实际上取决于您希望如何将 rgb 值编码为字符。一种方法是让一个字符代表其中一种颜色的亮度——因此需要三个字符来代表一个像素。另一点要确定的是,你的字符将只代表 0 到 63 之间的值,而不是通常的 0 到 255。因此你需要将每个值乘以 4,这样图像就不会太暗。

下面是我将如何重写 encode 函数:

img = Image.new("RGB", size)  # RGB image

ind = 0

for row in range(0, size[0]):

    for col in range(0, size[1]):

        if ind <= text_length - 3:  # only change pixel value for length of text

            r = convert_char_to_int(text[ind], limit=64) * 4
            g = convert_char_to_int(text[ind+1], limit=64) * 4
            b = convert_char_to_int(text[ind+2], limit=64) * 4

            img.putpixel((row, col), (r, g, b))

            ind += 3

        else:  # end of text, leave remaining pixel(s) black to indicate null

            break

img.save(result_path)

return result_path

我怀疑你想将不同的字符编码到不同的颜色通道中:

for row in range(0, size[0]):
    for col in range(0, size[1]):

        if ind >= text_length : break # only change pixel value for length of text

        r = convert_char_to_int(text[ind], limit=limit)
        ind = max( ind+1, text_length - 1)  # don't go beyond text length
        g = convert_char_to_int(text[ind], limit=limit)
        ind = max( ind+1, text_length - 1)
        b = convert_char_to_int(text[ind], limit=limit)
        ind += 1

        img.putpixel((row, col), (r,g,b))