python练手项目(1)——字符图片生成

python练手项目(1)——字符图片生成

设计思路

  1. 读入图片并读取图片的像素
  2. 将像素映射至字符
  3. 组合字符并写入文件

使用模块

  • pillow
    python的一种GUI库,其中最主要的是Image类,相关教程链接
  • argparse
    argparse是python用于解析命令行参数和选项的标准模块,用于代替已经过时的optparse模块,相关教程链接

源码以及解析

# the packages needed
from PIL import Image
import argparse

# All of the ASCii characters are stored in a list,
# can be modified by your own characters
ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
# construct a argument parse instance
parse = argparse.ArgumentParser()
# add arguments to parse
parse.add_argument('file')
parse.add_argument('-o', '--output')
parse.add_argument('--width', type=int, default=80)
parse.add_argument('--height', type=int, default=80)

args = parse.parse_args()
# read arguments to variables
IMG = args.file         # this argument is the file name
WIDTH = args.width      # the width of the img should be
HEIGHT = args.height    # the height of the img should be
OUTPUT = args.output    # the file to store the char-picture

def get_char(r, g, b, alpha = 256):
    """Translate a tuple of RGB data to gray scale
       Using a simple algorithm: gray = 0.2126*r + 0.7152*g + 0.0722*b
       and some gray level value correspond to a specific char
    """
    length = len(ascii_char)
    gray = int(0.2126*r + 0.7152*g + 0.0722*b)
    unit = (256.0+1)/length
    if alpha == 0:  # corresponding to the RGB=(0, 0, 0)
        return ' '
    return ascii_char[int(gray/unit)]

if __name__ == '__main__':
    # If this python file is the main file, run following codes
    im = Image.open(IMG)   # open the Image file
    im = im.resize((WIDTH, HEIGHT), Image.NEAREST)  # reset the size of the image

    txt = ""

    for i in range(HEIGHT):
        for j in range(WIDTH):
            txt += get_char(*im.getpixel((j, i)))  # *im.getpixel unzipped to: r, g, b, alpha
        txt += '\n'
    print txt

    if OUTPUT:  # write with specific file name
        with open(OUTPUT,'w') as f:
            f.write(txt)
    else:   # write with default file name
        with open("output.txt",'w') as f:
            f.write(txt)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值