返回

用Python将图片转为彩色字符画

发布时间:2022-12-19 08:31:45 259

说实话,原本我也没想到做个字符画还能有续集。今天搜教程,看到了有彩色版的转换方式。有了之前两个教程的基础,既解决了基本的字符处理问题( 用Python将图片转为字符画 ),又解决了界面问题( 用Python实现简易计算器 ),这次的实践就是轻松加愉快了。

from PIL import Image, ImageFont, ImageDraw
from tkinter import filedialog, Tk

def open_path():
root = Tk()
root.withdraw()
file_path = (filedialog.askopenfilename(title='选择图片文件', filetypes=[('All Files', '*')]))
return file_path

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

print('正在转换......')

def get_char(r, g, b, alpha=256): # alpha透明度
if alpha == 0:
return ' '
length = len(ascii_char)
gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
unit = (256.0 + 1) / length
return ascii_char[int(gray / unit)]

def save_path():
# 保存图片路径
root = Tk()
root.withdraw()
file_path = (filedialog.asksaveasfilename(title='保存路径', filetypes=[('All Files', '*')]))
return file_path

if __name__ == '__main__':
img = Image.open(IMG)
WIDTH = int(img.width / 6)
HEIGHT = int(img.height / 15)
img_txt = Image.new("RGB", (img.width, img.height), (255, 255, 255))
img = img.resize((WIDTH, HEIGHT), Image.NEAREST)
txt = ""
colors = []
for i in range(HEIGHT):
for j in range(WIDTH):
pixel = img.getpixel((j, i))
colors.append((pixel[0], pixel[1], pixel[2])) # 记录像素颜色信息
if (len(pixel) == 4):
txt += get_char(pixel[0], pixel[1], pixel[2], pixel[3])
else:
txt += get_char(pixel[0], pixel[1], pixel[2])
txt += '\n'
colors.append((255, 255, 255))
dr = ImageDraw.Draw(img_txt)
font = ImageFont.load_default().font
x = y = 0
# 获取字体的宽高
font_w, font_h = font.getsize(txt[1])
font_h *= 1.37
# 为每个ascii进行上色
for i in range(len(txt)):
if (txt[i] == '\n'):
x += font_h
y = -font_w
dr.text([y, x], txt[i], colors[i])
y += font_w

print('转换成功!')
print('请选择保存路径:')
save_path = save_path()+'.png'
img_txt.save(save_path)
print('保存成功')
img = Image.open(save_path)
img.show()

如果没有基础,可以看前面两篇了解一下,这次就直接上代码吧。

原图片、完成图、细节图如下。

用Python将图片转为彩色字符画_Image

[2022年07月12日原始发布于本作者博客]

>>查看原文:​https://www.gsgundam.com/archive/2022-07-12-how-to-draw-image-ascii-color-python-pil-tkinter/​

特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
精选文章
thumb 中国研究员首次曝光美国国安局顶级后门—“方程式组织”
thumb 俄乌线上战争,网络攻击弥漫着数字硝烟
thumb 从网络安全角度了解俄罗斯入侵乌克兰的相关事件时间线