使用 Python 将图像转换为 ASCII Art

在本教程中,我们将学习如何使用 Python 编程语言将任何图像转换为 ASCII 艺术。我相信您听说过 ASCII 艺术,这是一种使用可打印 ASCII 字符来显示图像的图形设计技术。请看下图的示例。

图3

现在我们已经清楚了在本教程结束时我们的目标是什么。我们不要再浪费时间了,开始代码实现吧。

使用 Python 从图像创建 ASCII 艺术

在本节中,您将学习如何使用 Python 从图像生成 ASCII 艺术作品。

加载图像

第一步也是最重要的一步是使用 PIL 库将图像加载到我们的程序中。我们将利用异常处理来确保我们事先处理错误。我们将使用标志变量来了解图像是否在系统中。

推荐阅读:Python 异常处理 – Python try-except

1
2
3
4
5
6
7
8
9
10
import PIL.Image
 
img_flag = True
path = input("Enter the path to the image field : \n")
 
try:
  img = PIL.Image.open(path)
  img_flag = True
except:
  print(path, "Unable to find image ")

调整图像大小

我们需要将图像的大小调整为较小的宽度和高度,这样它就不会出现太大的文本并造成混乱。

1
2
3
4
5
width, height = img.size
aspect_ratio = height/width
new_width = 120
new_height = aspect_ratio * new_width * 0.55
img = img.resize((new_width, int(new_height)))

将图像转换为灰度

我们可以使用该 convert 函数并传递灰度图像输出的选项 L 。

img = img.convert('L')

创建 ASCII 字符列表

请记住,ASCII 字符按从最暗到最亮的顺序排列,这意味着对于下面显示的列表,最暗的像素将替换为 , @ 最亮的像素将替换为 .您可以根据自己的喜好更改列表。

chars = ["@", "J", "D", "%", "*", "P", "+", "Y", "$", ",", "."]

转换为 ASCI 艺术

要将图像转换为 ASCII 字符,我们获取图像中每个像素的像素值,并将相应的 ASCII 字符映射在一起以形成一个新字符串。现在,我们使用  函数 to_greyscale 将图像转换  为 ASCII 艺术!我们还将生成的文本保存到文件中。GreyScale imagepixel_to_ascii

1
2
3
4
5
6
7
8
9
10
11
12
13
pixels = img.getdata()
new_pixels = [chars[pixel//25] for pixel in pixels]
new_pixels = ''.join(new_pixels)
 
# split string of chars into multiple strings of length equal to new width and create a list
new_pixels_count = len(new_pixels)
ascii_image = [new_pixels[index:index + new_width] for index in range(0, new_pixels_count, new_width)]
ascii_image = "\n".join(ascii_image)
print(ascii_image)
 
# write to a text file.
with open("sample_ascii_image.txt", "w") as f:
 f.write(ascii_image)

完整代码

让我们看一下上一节中刚刚编写的完整代码。

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
import PIL.Image
 
img_flag = True
path = input("Enter the path to the image field : \n")
 
try:
  img = PIL.Image.open(path)
  img_flag = True
except:
  print(path, "Unable to find image ");
 
width, height = img.size
aspect_ratio = height/width
new_width = 120
new_height = aspect_ratio * new_width * 0.55
img = img.resize((new_width, int(new_height)))
 
img = img.convert('L')
 
chars = ["@", "J", "D", "%", "*", "P", "+", "Y", "$", ",", "."]
 
pixels = img.getdata()
new_pixels = [chars[pixel//25] for pixel in pixels]
new_pixels = ''.join(new_pixels)
new_pixels_count = len(new_pixels)
ascii_image = [new_pixels[index:index + new_width] for index in range(0, new_pixels_count, new_width)]
ascii_image = "\n".join(ascii_image)
 
with open("ascii_image.txt", "w") as f:
 f.write(ascii_image)

一些示例输出

图4
图5

结论

继续用许多不同的角色尝试这个练习,然后亲自看看结果。您可能还会发现一些非常有趣的结果!请在下面的评论中告诉我们哪一种最适合您。