zoukankan      html  css  js  c++  java
  • 图片处理拓展篇 : 图片转字符画(ascii)

    首先要明确思路, 图片是由像素组成的, 不同的像素有不同的颜色(rgb), 那么既然我们要转化为字符画, 最直接的办法就是利用字符串来替代像素, 也就是用不同的字符串来代表不同的像素. 另外图片一般来讲是彩色的, 而acsii(一般打印在终端上吧) 都是黑白的, 此时就要介绍另外一个概念了 :

    灰度值:指黑白图像中点的颜色深度,范围一般从0到255,白色为255,黑色为0,故黑白图片也称灰度图像.

    到这里思路就很明确了, 我们要做的就是两件事 :

    1. 将每一个像素点(彩色图片用rgb)映射到每一个灰度值...

    2. 将灰度值映射到每一个字符串...

    所以我们还需要从像素点的rgb到灰度值的转换公式 :  灰度值 = 0.2126 * r + 0.7152 * g + 0.0722 * b.

    代码如下 :

     1 from PIL import Image
     2 
     3 ascii_chars = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/|()1{}[]?-_+~<>i!lI;:,"^`'.")   #用来替代像素的字符集合...
     4 
     5 def get_chars(r, g, b, alpha = 256):
     6     global ascii_chars
     7     if alpha == 0:
     8         return ' '
     9     length = len(ascii_chars)
    10     gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
    11     unit = alpha / length                 #将256个像素均分给字符...
    12     return ascii_chars[int(gray/unit)]
    13 
    14 
    15 
    16 imagePath = "/Users/zhangzhimin/ascii_dora.png"
    17 outPutHeight = 70
    18 outPutWidth = 100
    19 
    20 
    21 img = Image.open(imagePath)
    22 img = img.resize((outPutWidth, outPutHeight))
    23 
    24 
    25 txt = ""
    26 for y in range(outPutHeight):
    27     for x in range(outPutWidth):
    28         txt += get_chars(*img.getpixel((x, y)))
    29     txt += '
    '
    30 
    31 print(txt)

    效果大概是这样的 : 

    值得一提的是只对一些层次简单的图形会有很好的效果, 如果想要解析复杂的图片建议增加字符串的个数以及显示屏的大小...

    感谢实验楼提供这样一个有趣的编程练习...

  • 相关阅读:
    Javascript FP-ramdajs
    微信小程序开发
    SPA for HTML5
    One Liners to Impress Your Friends
    Sass (Syntactically Awesome StyleSheets)
    iOS App Icon Template 5.0
    React Native Life Cycle and Communication
    Meteor framework
    RESTful Mongodb
    Server-sent Events
  • 原文地址:https://www.cnblogs.com/nzhl/p/5599346.html
Copyright © 2011-2022 走看看