美麗Python:將圖片轉換成ASCII圖案的藝術
很多年前,我還在大學上學,參加了一個由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
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!