python - How to understand the operation of converting RGB values ​​​​to characters in PIL
高洛峰
高洛峰 2017-06-12 09:26:11
0
2
796
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

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
我想大声告诉你

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

習慣沉默

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template