python将图片转成ascii码代码

代码语言:python

所属分类:其他

代码描述:python将图片转成ascii码代码,使用了PIL与typing库实现。

代码标签: python 图片 ascii 代码

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

#!/usr/bin/env python3

from typing import Tuple, NewType
from PIL import Image


Pixel = NewType("Pixel", Tuple[int, int, int, int])
 
CHARACTERS = (' ', '.', 'o', '*', 'o', 'O', '#', '@')
 
MAX_CHANNEL_INTENSITY = 255
MAX_CHANNEL_VALUES = MAX_CHANNEL_INTENSITY * 4 # 4 is the number of channels of a Pixel
 

 
def map_intensity_to_character(intensity: float) -> CHARACTERS:
    return CHARACTERS[round(intensity * len(CHARACTERS))]
 
 
def get_pixel_intensity(pixel: Pixel) -> float:
    return sum(pixel) / 1020 # 1020 = 255 * 4
 
 
def print_ascii_art(size: Tuple[int, int], characters: str):
    index = 0
    for _ in range(size[1]):
        print(characters[index:index+size[0]])
        index += size[0]
 
 

def convert_image(image: Image) -> str:
    ascii_string = ''
    for pixel in image.getdata():
        intensity = get_pixel_.........完整代码请登录后点击上方下载按钮下载查看

网友评论0