美丽Python:将图片转换成ASCII图案的艺术
jopen 10年前
很多年前,我还在大学上学,参加了一个由FOSSEE组织的学习小组,在那里,我第一次知道了“Python”,并深深的喜欢上了它。它的简单、对复杂问题的优雅解决方案让我吃惊。下面的这个图片转ASCII码工具就是我在这个学习小组里学到的。
工作原理
我首先将给定的图片缩放到一个适合用ASCII表现的分辨率尺寸。让后再将图片转换成灰度级图片(黑白图片)。在黑白图片模式下,灰度有256个等 级,换句话说,每个像素的明暗度是用一个8 bit的值表示。0 表示颜色是黑色,256表示颜色是白色。我们把0-256分成11个小区间,每一个小区间用一个ASCII字符表示。并且字符表现出的颜色深浅要和这个区 间的灰度相匹配。我使用PIL库处理图片。下面的代码写的很明白,你一定能看懂。对于不同的图片,输出的效果可能有些不同,效果有好有差,但你可以通过调 整这11个ASCII来测试生成的效果。
依赖的库
PIL(Python Imaging Library)
在Ubuntu环境下
$ sudo pip install Pillow
代码:
from PIL import Image
ASCII_CHARS = [ '#', '?', '%', '.', 'S', '+', '.', '*', ':', ',', '@'] def scale_image(image, new_width=100): """Resizes an image preserving the aspect ratio. """ (original_width, original_height) = image.size aspect_ratio = original_height/float(original_width) new_height = int(aspect_ratio * new_width) new_image = image.resize((new_width, new_height)) return new_image def convert_to_grayscale(image): return image.convert('L') def map_pixels_to_ascii_chars(image, range_width=25): """Maps each pixel to an ascii char based on the range in which it lies. 0-255 is divided into 11 ranges of 25 pixels each. """ pixels_in_image = list(image.getdata()) pixels_to_chars = [ASCII_CHARS[pixel_value/range_width] for pixel_value in pixels_in_image] return "".join(pixels_to_chars) def convert_image_to_ascii(image, new_width=100): image = scale_image(image) image = convert_to_grayscale(image) pixels_to_chars = map_pixels_to_ascii_chars(image) len_pixels_to_chars = len(pixels_to_chars) image_ascii = [pixels_to_chars[index: index + new_width] for index in xrange(0, len_pixels_to_chars, new_width)] return "\n".join(image_ascii) def handle_image_conversion(image_filepath): image = None try: image = Image.open(image_filepath) except Exception, e: print "Unable to open image file {image_filepath}.".format(image_filepath=image_filepath) print e return image_ascii = convert_image_to_ascii(image) print image_ascii if __name__=='__main__': import sys image_file_path = sys.argv[1] handle_image_conversion(image_file_path)
欢迎报告bug和提出改进意见!
(英文,CC Licensed)
来自:http://netsmell.com/beautiful-python-a-simple-ascii-art-generator-from-images.html