直接上代码:
from PIL import Image
char = list('M3NB6Q#OC?7>!:–;. ')
def get_char(r, g, b, alpha=256):
if alpha == 0:
return ' '
grey = (2126 * r + 7152 * g + 722 * b) / 10000
char_idx = int((grey / (alpha + 1.0)) * len(char))
return char[char_idx]
def write_file(out_file_name, content):
with open(out_file_name, 'w') as f:
f.write(content)
def main(file_name="input.jpg", width=100, height=80, out_file_name='output.txt'):
text = ''
im = Image.open(file_name)
im = im.resize((width, height), Image.NEAREST)
for i in range(height):
for j in range(width):
g = im.getpixel((j, i))
#print('g:',g)
text += get_char(*g)
text += '\n'
print(text)
write_file(out_file_name, text)
if __name__ == '__main__':
main('dance.png')
执行后报错:TypeError: __main__.get_char() argument after * must be an iterable, not int
原因:getpixel用法,返回值会根据图片变化, :returns: The pixel value. If the image is a multi-layer image, this method returns a tuple. 如果是一个多层图片,返回一个元组,换句话说,如果不是,则返回可能是一个数值,非元组。
解决办法:需要转换一下,如下: txt += get_char(*im.convert('RGBA').getpixel((j,i))) 先换成RGBA的 multi-layer image
优化后代码如下:
def main(file_name="input.jpg", width=100, height=80, out_file_name='output.txt'):
text = ''
im = Image.open(file_name)
im = im.resize((width, height), Image.NEAREST)
for i in range(height):
for j in range(width):
g = im.convert('RGBA').getpixel((j, i))
#print('g:',g)
text += get_char(*g)
text += '\n'
print(text)
write_file(out_file_name, text)
标签:__,TypeError,name,get,text,char,im,file From: https://www.cnblogs.com/yimobaihe/p/16724027.html