看到一个问题,问如何把刘看山 Python 化?这个有点意思,想想也好久没动过 Python 了,就来个字符画风格的刘看山吧。
具体代码:
# by gua
from PIL import Image
class Iamge2ASCIIArt():
"""Convert image to ASCII Art"""
def __init__(self, art_char, image_path):
self.__art_char = art_char
self.__image_path = image_path
def __rgb2lib(self, r, g, b):
return int(0.212671*r + 0.715160*g + 0.072169*b)
def __fetch_char(self, r, g, b):
gray = self.__rgb2lib(r, g, b)
gray_width = 256 / len(self.__art_char)
return self.__art_char[int(gray/gray_width)]
def __get_image(self):
return Image.open(self.__image_path)
def __resize_iamge(self, img, percent):
width, height = int(img.size[1]*percent), int(img.size[0]*percent)
return img.resize((width, height))
def do(self):
img = self.__get_image()
img = self.__resize_iamge(img, 0.1)
width, height = img.size
for h in range(height):
text = ""
for w in range(width):
r, g, b = img.getpixel((w, h))
text += self.__fetch_char(r, g, b)
if h == height-10:
text = text[0:height//4] + " 人生苦短,我用 Python " + text[height//4+23:]
print(text)
if __name__ == '__main__':
lks = Iamge2ASCIIArt("#*.@&+", "./user_avatar 07.png")
lks.do()
解释:
- 第一步
def __init__(self, art_char, image_path):
self.__art_char = art_char
self.__image_path = image_path
这里初始化字符画要用到的各个字符,是一个字串。同时初始化待处理图像的路径。
- 第二步
def __rgb2lib(self, r, g, b):
return int(0.212671*r + 0.715160*g + 0.072169*b)
RBG 模式转换为 Lib 模式,Lab 模式是将图片转换成灰度图时经常用到的。
- 第三步
def __fetch_char(self, r, g, b):
gray = self.__rgb2lib(r, g, b)
gray_width = 256 / len(self.__art_char)
return self.__art_char[int(gray/gray_width)]
根据获得的灰度,及计算出来的灰度区间宽度,获取字串中对应的字符并作用于字符画。
- 第四步
def __get_image(self):
return Image.open(self.__image_path)
获取图像。
- 第五步
def __resize_iamge(self, img, percent):
width, height = int(img.size[1]*percent), int(img.size[0]*percent)
resize 图片大小。
- 第六步
def do(self):
img = self.__get_image()
img = self.__resize_iamge(img, 0.1)
width, height = img.size
for h in range(height):
text = ""
for w in range(width):
r, g, b = img.getpixel((w, h))
text += self.__fetch_char(r, g, b)
if h == height-10:
text = text[0:height//4] + " 人生苦短,我用 Python " + text[height//4+23:]
print(text)
处理字符画的生成及打印。
喜欢就点赞。在喜欢就评论~