python图片转字符画代码是什么


本文摘自php中文网,作者coldplay.xixi,侵删。

python图片转字符画代码 :首先计算出图片颜色对应的灰度值;然后根据灰度值,从字符集中获取图片中每个像素点对应的字符,代码为【args = parser.parse_args()】。

本教程操作环境:windows7系统、python3.9版,DELL G3电脑,该方法适用于所有品牌电脑。

相关免费学习推荐:python视频教程

原理

1、计算出图片颜色对应的灰度值,计算公式如下

1

gray = 0.2126 * r + 0.7152 * g + 0.0722 * b

2、根据灰度值,从字符集中获取图片中每个像素点对应的字符

代码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

# !/usr/bin/env python

# -*- coding:utf-8 -*-

from PIL import Image

import argparse

#命令行输入参数处理

parser = argparse.ArgumentParser()

parser.add_argument('file')   #输入文件

parser.add_argument('-o', '--output')  #输出文件

parser.add_argument('--width', type = int, default = 50) #输出字符画宽

parser.add_argument('--height', type = int, default = 50) #输出字符画高

#获取参数

args = parser.parse_args()

IMG = args.file

WIDTH = args.width

HEIGHT = args.height

OUTPUT = args.output

# 字符画使用的字符集

ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")

def get_char(r,g,b,alpha = 256):

  """将256灰度映射到70个字符上"""

  if alpha == 0:

    return ' '

  length = len(ascii_char)

  # 计算灰度的公式

  gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)

  unit = (256.0 + 1)/length

  index=int(gray/unit)

  return ascii_char[index]

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'

  print(txt)

  #字符画输出到文件

  if OUTPUT:

    with open(OUTPUT,'w') as f:

      f.write(txt)

  else:

    with open("output.txt",'w') as f:

      f.write(txt)z

运行结果

ee75f0cd19cf363b6c7498c8cfb6ad7.png

9813fb24bf6e365f1d0cb78739e5bb9.png

以上就是python图片转字符画代码是什么的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python属于什么类型的语言

Python 如何运行文件

Python最简单的网页爬虫教程

Python实现购物车程序

Python中列表中的pop方法与remove方法有什么区别

Python里format什么意思

Python中字符串数组如何逆序排列

Python unittest实现api自动化测试_Python

Python入门能做什么

如何加速Python程序

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...