Python 實現圖片轉字符畫,靜態圖、GIF 都能轉

字符畫是一種由字母、標點或其餘字符組成的圖畫,它產生於互聯網時代,在聊天軟件中使用較多,本文咱們看一下如何將本身喜歡的圖片轉成字符畫。python

靜態圖片

首先,咱們來演示將靜態圖片轉爲字符畫,功能實現主要用到的 Python 庫爲 OpenCV,安裝使用 pip install opencv-python 命令便可。canvas

功能實現的基本思路爲:利用聚類將像素信息聚爲 3 或 5 類,顏色最深的一類用數字密集度表示,陰影的一類用橫槓(-)表示,明亮部分用空白表示。app

主要代碼實現以下:dom

def img2strimg(frame, K=5):   
    if type(frame) != np.ndarray:
        frame = np.array(frame)
    height, width, *_ = frame.shape  
    frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    frame_array = np.float32(frame_gray.reshape(-1))
    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
    flags = cv2.KMEANS_RANDOM_CENTERS
    # 獲得 labels(類別)、centroids(矩心)
    compactness, labels, centroids = cv2.kmeans(frame_array, K, None, criteria, 10, flags)
    centroids = np.uint8(centroids)
    # labels 的數個矩心以隨機順序排列,因此須要簡單處理矩心
    centroids = centroids.flatten()
    centroids_sorted = sorted(centroids)
    # 得到不一樣 centroids 的明暗程度,0 爲最暗
    centroids_index = np.array([centroids_sorted.index(value) for value in centroids])
    bright = [abs((3 * i - 2 * K) / (3 * K)) for i in range(1, 1 + K)]
    bright_bound = bright.index(np.min(bright))
    shadow = [abs((3 * i - K) / (3 * K)) for i in range(1, 1 + K)]
    shadow_bound = shadow.index(np.min(shadow))
    labels = labels.flatten()
    # 將 labels 轉變爲實際的明暗程度列表
    labels = centroids_index[labels]
    # 解析列表
    labels_picked = [labels[rows * width:(rows + 1) * width:2] for rows in range(0, height, 2)]
    canvas = np.zeros((3 * height, 3 * width, 3), np.uint8)
    # 建立長寬爲原圖三倍的白色畫布
    canvas.fill(255)
    y = 8
    for rows in labels_picked:
        x = 0
        for cols in rows:
            if cols <= shadow_bound:
                cv2.putText(canvas, str(random.randint(2, 9)),
                            (x, y), cv2.FONT_HERSHEY_PLAIN, 0.45, 1)
            elif cols <= bright_bound:
                cv2.putText(canvas, "-", (x, y),
                            cv2.FONT_HERSHEY_PLAIN, 0.4, 0, 1)
            x += 6
        y += 6
    return canvas

原圖以下:

效果圖以下:
字體

GIF 動圖

接下來咱們演示將 GIF 轉爲字符畫,功能實現主要用到的 Python 庫爲 imageio、Pillow,安裝使用 pip install imageio/Pillow 命令便可。ui

功能實現的基本思路以下:spa

  • 將 gif 圖片的每一幀拆分爲靜態圖片
  • 將全部靜態圖片變爲字符畫
  • 將全部字符畫從新合成 gif

主要代碼實現以下:code

# 拆分 gif 將每一幀處理成字符畫
def gif2pic(file, ascii_chars, isgray, font, scale):
    '''
    file: gif 文件
    ascii_chars: 灰度值對應的字符串
    isgray: 是否黑白
    font: ImageFont 對象
    scale: 縮放比例
    '''
    im = Image.open(file)
    path = os.getcwd()
    if(not os.path.exists(path+"/tmp")):
        os.mkdir(path+"/tmp")
    os.chdir(path+"/tmp")
    # 清空 tmp 目錄下內容
    for f in os.listdir(path+"/tmp"):
        os.remove(f)
    try:
        while 1:
            current = im.tell()
            name = file.split('.')[0]+'_tmp_'+str(current)+'.png'
            # 保存每一幀圖片
            im.save(name)
            # 將每一幀處理爲字符畫
            img2ascii(name, ascii_chars, isgray, font, scale)
            # 繼續處理下一幀
            im.seek(current+1)
    except:
        os.chdir(path)

# 將不一樣的灰度值映射爲 ASCII 字符
def get_char(ascii_chars, r, g, b):
    length = len(ascii_chars)
    gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
    return ascii_chars[int(gray/(256/length))]


# 將圖片處理成字符畫
def img2ascii(img, ascii_chars, isgray, font, scale):
    scale = scale
    # 將圖片轉換爲 RGB 模式
    im = Image.open(img).convert('RGB')
    # 設定處理後的字符畫大小
    raw_width = int(im.width * scale)
    raw_height = int(im.height * scale)
    # 獲取設定的字體的尺寸
    font_x, font_y = font.getsize(' ')
    # 肯定單元的大小
    block_x = int(font_x * scale)
    block_y = int(font_y * scale)
    # 肯定長寬各有幾個單元
    w = int(raw_width/block_x)
    h = int(raw_height/block_y)
    # 將每一個單元縮小爲一個像素
    im = im.resize((w, h), Image.NEAREST)
    # txts 和 colors 分別存儲對應塊的 ASCII 字符和 RGB 值
    txts = []
    colors = []
    for i in range(h):
        line = ''
        lineColor = []
        for j in range(w):
            pixel = im.getpixel((j, i))
            lineColor.append((pixel[0], pixel[1], pixel[2]))
            line += get_char(ascii_chars, pixel[0], pixel[1], pixel[2])
        txts.append(line)
        colors.append(lineColor)
    # 建立新畫布
    img_txt = Image.new('RGB', (raw_width, raw_height), (255, 255, 255))
    # 建立 ImageDraw 對象以寫入 ASCII
    draw = ImageDraw.Draw(img_txt)
    for j in range(len(txts)):
        for i in range(len(txts[0])):
            if isgray:
                draw.text((i * block_x, j * block_y), txts[j][i], (119,136,153))
            else:
                draw.text((i * block_x, j * block_y), txts[j][i], colors[j][i])
    img_txt.save(img)

# 讀取 tmp 目錄下文件合成 gif
def pic2gif(dir_name, out_name, duration):
    path = os.getcwd()
    os.chdir(dir_name)
    dirs = os.listdir()
    images = []
    num = 0
    for d in dirs:
        images.append(imageio.imread(d))
        num += 1
    os.chdir(path)
    imageio.mimsave(out_name + '_ascii.gif',images,duration = duration)

原圖以下:

黑白效果圖以下:

彩色效果圖以下:
對象

總結

本文咱們利用 Python 演示了將靜態圖和 GIF 轉爲字符畫的方法,你們若是有興趣的話,能夠將本身喜歡的圖轉一下,若是對轉換效果不滿意,還能夠修改代碼,改爲本身滿意的效果。blog

源碼在公衆號 Python小二 後臺回覆 字符畫 獲取。

本文非首發於我的號
相關文章
相關標籤/搜索