问题描述
这是我的代码
from PIL import Image
ASCII_CHARS = ["@","#","$"," ","-","|",":","."," " ]
def resize_image(image,new_width=50):
width,height = image.size
ratio = height/width
new_height = int(new_width * ratio)
resized_image = image.resize((new_width,new_height))
#resized_image.save('output.png')
return(resized_image)
def grayify(image):
grayscale_image = image.convert("L")
#grayscale_image.save('output.png')
return(grayscale_image)
# convert pixels to a string of ascii characters
def pixels_to_ascii(image):
pixels = image.getdata()
characters = ''.join([ASCII_CHARS[pixel//25] for pixel in pixels])
return(characters)
def main(new_width=50):
# attempt to open image from user-input
#path = input("Enter a valid pathname to an image:\n")
try:
image = Image.open("picachu.jpg")
except:
print(path," is not a valid pathname to an image.")
return
# convert image to ascii
new_image_data = pixels_to_ascii(grayify(resize_image(image)))
# format
pixel_count = len(new_image_data)
ascii_image = '\n'.join([new_image_data[index:(index+new_width)] for index in range(0,pixel_count,new_width)])
with open("full_image.txt","w") as f:
f.write(ascii_image)
fa = open("full_image.txt","r")
fb = open("trimmed_image.txt","w")
lines = fa.readlines()
fa.close()
lines = filter(lambda x: not x.isspace(),lines)
fb.write("".join(lines))
fb.close()
main()
对于picachu.jpg输出如下:
|-
$
|#$
##.
.: | #.
:## : ..:$.
|### .. ...|.
|## ..::. :...
:#$....:: :..:
. |.....:. :..:
:|::...:. ...:
:|::..::::.:::. ...:
.:|:..........:....::
::...........::.:.
:.............:.|
...:............::
.. -:...........:.
..$$ ............
.|.| |.......|:-..
- ......::... $.:
. :..:- -...-#-.:
: :... $ -......
. -....--- $-....:: ..::
|:....||||-:...| -:....:
......|||-:...: |.....:
:....|--|....| :....::
.::::::..||.....| |....:::::::...
:.......::.......:|....::..........::..
..........::.....::....:|:..............:.
:.........:|::........:|:.:...............
..........|:.........:| ..:::............
:::::::||:.........|| ..||||:.........
:|||||:..........:| ::|||||::.....:
:::.............| ::||::|||::..:
................: .::|. .:|::
:................ |::.:|
.................: :|:.|.
.................: :||:|
:..................: -
:.................- $-
...................: -
:....................
:....................
:..........::::::...:
.::::::::::||||||::..
||||||||||-||||||||.
:::|||. ..::|-|::|.
.-|:::. ...::-:
.. ..
因此,代码没有问题!但问题是我想使用盲文字母“⡿⡾⡹⡲⡱⠶⠷⠸”而不是“ @#|-等” 当我尝试时:
ASCII_CHARS = ["\u280F"," "]
它给了我这个错误UnicodeEncodeError: 'charmap' codec can't encode character '\u280f' in position 317: character maps to <undefined>
有人知道如何解决此问题吗? 您可以找到其他盲文字符Unicode和十进制代码here
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)