图片转字符画

placekitten是一个图片网站,里面全是猫,后面两个参数是图片尺寸
所以可以改成输入任意尺寸,利用字符串拼接来爬取需要的图片

""" 
    2019/10/3
    version: 1.0.0
    by Zeronera
    实现图片爬取再到字符画的转化
"""
from PIL import Image
import requests

url = "http://placekitten.com/1000/1000"
r = requests.get(url)
with open("cat.png",'wb') as f:
    f.write(r.content)

img = Image.open("cat.png").convert('L')
width, height = img.size
img = img.resize((int(width*0.5), int(height*0.5)))
width, height = img.size
char_set = "@%#*+=-. "
text = ""

for row in range(height):
    for col in range(width):
        gray = img.getpixel((col, row))
        text += char_set[int(gray/255*8)]
    text += '\n'

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

猜你喜欢

转载自www.cnblogs.com/Zeronera/p/11619296.html