python图片转字符画 基于python实现图片转字符画代码实例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

python图片转字符画 基于python实现图片转字符画代码实例

橙子皮!   2021-03-15 我要评论
想了解基于python实现图片转字符画代码实例的相关内容吗,橙子皮!在本文为您仔细讲解python图片转字符画的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:python,图片,转,字符画,下面大家一起来学习吧。

直接上代码图片就使用我家爽妹子的吧

如果没有安装pil模块的话先cmd安装下

输入:pip install pillow

# -*- coding: utf-8 -*-
from PIL import Image

codeLib = '''@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,"^`'. '''#生成字符画所需的字符集
count = len(codeLib)

def transform1(image_file):
  image_file = image_file.convert("L")#转换为黑白图片,参数"L"表示黑白模式
  codePic = ''
  for h in range(0,image_file.size[1]): #size属性表示图片的分辨率,'0'为横向大小,'1'为纵向
    for w in range(0,image_file.size[0]):
      gray = image_file.getpixel((w,h)) #返回指定位置的像素,如果所打开的图像是多层次的图片,那这个方法就返回一个元组
      codePic = codePic + codeLib[int(((count-1)*gray)/256)]#建立灰度与字符集的映射
    codePic = codePic+'\r\n'
  return codePic

def transform2(image_file):
  codePic = ''
  for h in range(0,image_file.size[1]):
    for w in range(0,image_file.size[0]):
      g,r,b = image_file.getpixel((w,h))
      gray = int(r* 0.299+g* 0.587+b* 0.114)
      codePic = codePic + codeLib[int(((count-1)*gray)/256)]
    codePic = codePic+'\r\n'
  return codePic
fp = open(r'C:\路径\3.jpg','rb')
image_file = Image.open(fp)
image_file=image_file.resize((int(image_file.size[0]*0.2), int(image_file.size[1]*0.1)))#调整图片大小
print (u'Info:',image_file.size[0],' ',image_file.size[1],' ',count)

tmp = open('tmp.txt','w')
tmp.write(transform1(image_file))
tmp.close()
a,b,c=1,2,3
print(a,b,c)

结果不知还能否看出来

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们