作者 |周萝卜
来源 |萝卜大杂烩
#Importtypesforclarity
fromtypingimportNewType,Tuple
#Maximumvaluethesumofthepixel'schannelvaluescanreach
MAX_CHANNEL_VALUES=255*4
#DefininganRGBApixeltypeasatupleof4integers
Pixel=NewType("Pixel",Tuple[int,int,int,int])
#Returnsthepixel'sintensityvalueasafloat
defget_pixel_intensity(pixel:Pixel)->float:
#Sumofthepixel'schannelvaluesdividedbythemaximumpossibleintensity
returnsum(pixel)/MAX_CHANNEL_VALUES
为了清晰起见,我们在第一行导入了静态类型
#CharactersetforoutASCIIarts
CHARACTERS=('','.','°','*','o','O','#','@')
#Restunsthecharacterthatcorrespondstothegivenpixelintensity
defmap_intensity_to_character(intensity:float)->CHARACTERS:
returnCHARACTERS[round(intensity*len(CHARACTERS))]
#Importanimagelibraryforthesakeofsimplicity
fromPILimportImage
#Importargvforcommandlinearguments
fromsysimportargv
#TransformsanimageintoastringofASCIIcharacters
defconvert_image(image:Image)->str:
ascii_string=''
#Iterateovereverypixeloftheimage
forpixelinimage.getdata():
intensity=get_pixel_intensity(pixel)
character=map_intensity_to_character(intensity)
ascii_string+=character
returnascii_string
defmain():
#Gettheimagenamefromthecommandlineargumentslist
image_name=argv[1]
#OpentheimagefileusingthePILimagelibrary
image=Image.open(image_name)
#ConverttheimagetoastringofASCIIcharacters
ascii_image=convert_image(image)
if__name__=='__main__':
main()
#PrintsthegivenASCIIart
#sizeisaTuplecontainingthewidthandheightoftheimage
defprint_ascii_art(size:Tuple[int,int],characters:str):
index=0
#Iterateoveralltherowsoftheimage
for_inrange(size[1]):
#Printanumberofcharactersequaltothewidthoftheimage
#fromtheasciistring
print(characters[index:index+size[0]])
index+=size[0]
defmain():
image_name=argv[1]
image=Image.open(image_name)
ascii_image=convert_image(image)
#ActuallyprinttheASCIIimagetotheconsole
print_ascii_art(image.size,ascii_image)
pythonconverter.pyimage.png
#ThestartingpointofthegeneratedHTMLfile
HTML_TEMPLATE="""
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metahttp-equiv="X-UA-Compatible"content="IE=edge">
<metaname="viewport"content="width=device-width,initial-scale=1.0">
<title>ASCIIArt</title>
</head>
<body>
<divstyle="background-color:black;color:white;">
<pre>{}</pre>
</div>
</body>
</html>
"""
defascii_image_to_html(image_name:str,characters:str,size:Tuple[int,int]):
#OpenanHTMLfileforwritingwiththe'.html'extension
withopen(image_name+'.html','w')asimage_file:
ascii_image=''
index=0
#GeneratetheASCIIimageasexplainedbefore
for_inrange(size[1]):
#Manuallyaddanewlinecharacterattheendofeachroworcharacters
ascii_image+=characters[index:index+size[0]]+'\n'
index+=size[0]
#FinallywritetheASCIIstringtotheHTMLfileusingthetemplate
image_file.write(HTML_TEMPLATE.format(ascii_image))
defmain():
image_name=argv[1]
image=Image.open(image_name)
ascii_image=convert_image(image)
#SavetheresultinanHTMLfile
ascii_image_to_html(image_name,ascii_image,image.size)
#!/usr/bin/envpython3
fromtypingimportTuple,NewType
fromPILimportImage
fromsysimportargv
Pixel=NewType("Pixel",Tuple[int,int,int,int])
CHARACTERS=('','.','°','*','o','O','#','@')
MAX_CHANNEL_INTENSITY=255
MAX_CHANNEL_VALUES=MAX_CHANNEL_INTENSITY*4#4isthenumberofchannelsofaPixel
HTML_TEMPLATE="""
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metahttp-equiv="X-UA-Compatible"content="IE=edge">
<metaname="viewport"content="width=device-width,initial-scale=1.0">
<title>ASCIIArt</title>
</head>
<body>
<divstyle="background-color:black;color:white;line-height:10px">
<pre>{}</pre>
</div>
</body>
</html>
"""
defmap_intensity_to_character(intensity:float)->CHARACTERS:
returnCHARACTERS[round(intensity*len(CHARACTERS))]
defget_pixel_intensity(pixel:Pixel)->float:
returnsum(pixel)/1020#1020=255*4
defprint_ascii_art(size:Tuple[int,int],characters:str):
index=0
for_inrange(sie[1]):
print(characters[index:index+size[0]])
index+=size[0]
defascii_image_to_html(image_name:str,characters:str,size:Tuple[int,int]):
withopen(image_name+'.html','w')asimage_file:
ascii_image=''
index=0
for_inrange(size[1]):
ascii_image+=characters[index:index+size[0]]+'\n'
index+=size[0]
image_file.write(HTML_TEMPLATE.format(ascii_image))
defconvert_image(image:Image)->str:
ascii_string=''
forpixelinimage.getdata():
intensity=get_pixel_intensity(pixel)
character=map_intensity_to_character(intensity)
ascii_string+=character
returnascii_string
defmain()->None:
image_name=argv[1]
image=Image.open(image_name)
print(image.size,image.mode,image.size,image.getcolors())
ascii_image=convert_image(image)
#print_ascii_art(image.size,ascii_image)
ascii_image_to_html(image_name,ascii_image,image.size)
if__name__=='__main__':
main()
原文地址:https://towardsdatascience.com/convert-pictures-to-ascii-art-ece89582d65b
分享
点收藏
点点赞
点在看
文章转发自AI科技大本营微信公众号,版权归其所有。文章内容不代表本站立场和任何投资暗示。
Copyright © 2021.Company 元宇宙YITB.COM All rights reserved.元宇宙YITB.COM