小试牛刀2

一 图片转字符画 

  字符画,一种由字母、标点、汉字或其他字符组成的图画。

from PIL import Image

def gray_sacle(r,g,b):
    l = "abcdefghigklmnopqrstuvwxyzQWERTYUIOPASDFGHJKLZXCVBNM,./<>?;':[]{}\|~`!@#$%^&*()_+-="
    l = list(l)
    #这是一般公式
    gray_value = 0.3*r+0.6*g+0.1*b
    unit = 256/len(l)
    return l[int(gray_value/unit)]

if __name__ == '__main__':

    image = Image.open('a1.jpg')
    width,height = image.size
    width = int(width/2)
    height = int(height/2)
    # resize :Returns a resized copy of this image.
    image = image.resize((width,height))
    pic = ""
    for i in range(height):
        for j in range(width):
            #getpixel:Returns the pixel value at a given position.
            r,g,b = image.getpixel((j,i))
            pic += gray_sacle(r,g,b)
        pic += '\n'
    with open('a1.txt','w') as f:
        f.write(pic)

  反思:

    1 获取图片的每个像素的rgb。 getpixel() 

    2 彩色图片转变为灰度,一般按加权的方法转换,R, G,B 的比一般为3:6:1。

    3 最基本的算法都忘掉,不会了吗。在写gray_scale()函数,选取列表中某个索引。

posted @ 2018-02-14 17:47  骑者赶路  阅读(199)  评论(0编辑  收藏  举报