search

Home  >  Q&A  >  body text

python - How to understand the operation of converting RGB values ​​​​to characters in PIL

ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
def get_char(r,g,b,alpha = 256):
    if alpha == 0:
        return ' '
    length = len(ascii_char)
    gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)

    unit = (256.0 + 1)/length
    return ascii_char[int(gray/unit)]

if __name__ == '__main__':

    im = Image.open(IMG)
    im = im.resize((WIDTH,HEIGHT), Image.NEAREST)

    txt = ""

    for i in range(HEIGHT):
        for j in range(WIDTH):
            txt += get_char(*im.getpixel((j,i)))
        txt += '\n'

How to understand the data passed into the get_char function by get_char(*im.getpixel((j,i))), what variable does this belong to, and what is the operating principle of this function

高洛峰高洛峰2728 days ago776

reply all(2)I'll reply

  • 我想大声告诉你

    我想大声告诉你2017-06-12 09:28:11

    In the for loop, im.getpixel((j,i) refers to getting the rgb value of each corresponding coordinate pixel. You can get the value of a fixed coordinate and then print it out to see

    reply
    0
  • 習慣沉默

    習慣沉默2017-06-12 09:28:11

    In fact, RGB has its own theoretical system, which only implements corresponding operations through calculation of pixels. To put it simply, to give a simple example, such as (255, 255, 255), we convert the above numbers into hexadecimal, which are FF, FF, FF. When spliced ​​it becomes #FFFFF.

    reply
    0
  • Cancelreply