python学习之手把手教你将图片变成黑白或彩色字符画(骚操作)
文章目錄
- 前言
- 一、字符畫(huà)的實(shí)現(xiàn)原理
- 二、黑白字符畫(huà)實(shí)現(xiàn)代碼
- 三、彩色字符畫(huà)生成
- 代碼實(shí)現(xiàn):
- 總結(jié)
前言
字符畫(huà)這個(gè)話題,似乎早在貼吧時(shí)代就已經(jīng)被玩爛了。在百度圖片隨便一搜索,就能夠看到非常多。然后在這個(gè)時(shí)代,會(huì)編程的人越來(lái)越多(尤其是 MATLAB,Python 等非常適合圖像處理的腳本語(yǔ)言),類似的教程更是數(shù)不勝數(shù)。
一、字符畫(huà)的實(shí)現(xiàn)原理
字符畫(huà)是一系列字符的組合,我們可以把字符看作是比較大塊的像素,一個(gè)字符能表現(xiàn)一種顏色(暫且這么理解吧),字符的種類越多,可以表現(xiàn)的顏色也越多,圖片也會(huì)更有層次感。
問(wèn)題來(lái)了,我們是要轉(zhuǎn)換一張彩色的圖片,這么多的顏色,要怎么對(duì)應(yīng)到單色的字符畫(huà)上去?這里就要介紹灰度值的概念了。
灰度值:指黑白圖像中點(diǎn)的顏色深度,范圍一般從0到255,白色為255,黑色為0,故黑白圖片也稱灰度圖像
我們可以使用灰度值公式將像素的 RGB 值映射到灰度值:
gray = 0.2126 * r + 0.7152 * g + 0.0722 * b
這樣就好辦了,我們可以創(chuàng)建一個(gè)不重復(fù)的字符列表,灰度值小(暗)的用列表開(kāi)頭的符號(hào),灰度值大(亮)的用列表末尾的符號(hào)。
二、黑白字符畫(huà)實(shí)現(xiàn)代碼
demo.py test.jpg -o outfile.txt --width 90 --height 90
代碼如下(示例):
from PIL import Image import argparsedef get_char(r,g,b,a=256):if a == 0:return ' 'gray = 0.2126 * r + 0.7152 * g + 0.0722 * blength = len(ascii_str)unit = 256/lengthreturn ascii_str[int(gray/unit)]if __name__ == "__main__":parser = argparse.ArgumentParser()parser.add_argument('file') # 需要設(shè)置輸入文件parser.add_argument('-o', '--output') # 輸出文件parser.add_argument('--width', type=int, default=80) # 輸出字符畫(huà)寬parser.add_argument('--height', type=int, default=80) # 輸出字符畫(huà)高# 獲取參數(shù)args = parser.parse_args()IMG = args.fileWIDTH = args.widthHEIGHT = args.heightOUTPUT = args.outputascii_str = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")im = Image.open(IMG)im = im.resize((WIDTH,HEIGHT))txt = ''for i in range(HEIGHT):for j in range(WIDTH):txt += get_char(*im.getpixel((j,i))) # (r,g,b,a)txt += '\n'print(txt)#字符畫(huà)輸出到文件if OUTPUT:with open(OUTPUT,'w') as f:f.write(txt)else:with open("output.txt",'w') as f:f.write(txt)三、彩色字符畫(huà)生成
代碼實(shí)現(xiàn):
import numpy as np import cv2 from PIL import Image, ImageFont, ImageDraw, ImageFilter import random from pathlib import Path import time from tqdm import tqdmdef color(input: str,output: str = None,rows: int = 100,alphabet='uppercase',background='origin7',out_height: int = None,scale: float = None, ):"""output colorful text picture"""input_path = Path(input)# the original imageorigin = Image.open(input_path)width, height = origin.sizeprint(f'input size: {origin.size}')# text amount of the output imagetext_rows = rowstext_cols = round(width / (height / text_rows) * 1.25) # char height-width ratioorigin_ref_np = cv2.resize(np.array(origin), (text_cols, text_rows), interpolation=cv2.INTER_AREA)origin_ref = Image.fromarray(origin_ref_np)# font propertiesfontsize = 17font = ImageFont.truetype('courbd.ttf', fontsize)char_width = 8.88char_height = 11# output size depend on the rows and colscanvas_height = round(text_rows * char_height)canvas_width = round(text_cols * char_width)# a canvas used to draw texts on itcanvas = get_background(background, origin, canvas_width, canvas_height)print(f'canvas size: {canvas.size}')# start drawingsince = time.time()print(f'Start transforming {input_path.name}')draw = ImageDraw.Draw(canvas)charlist = get_alphabet(alphabet)length = len(charlist)for i in tqdm(range(text_cols)):for j in range(text_rows):x = round(char_width * i)y = round(char_height * j - 4)char = charlist[random.randint(0, length - 1)]color = origin_ref.getpixel((i, j))draw.text((x, y), char, fill=color, font=font)# resize the reproduct if necessaryif out_height: # height goes firstcanvas_height = out_heightcanvas_width = round(width * canvas_height / height)canvas = canvas.resize((canvas_width, canvas_height), Image.BICUBIC)elif scale:canvas_width = round(width * scale)canvas_height = round(height * scale)canvas = canvas.resize((canvas_width, canvas_height), Image.BICUBIC)# output filenameif output:output_path = Path(output)else:output_path = input_path.with_name(f'{input_path.stem}_{canvas_width}x{canvas_height}_D{text_rows}_{background}.png')canvas.save(output_path)print(f'Transformation completed. Saved as {output_path.name}.')print(f'Output image size: {canvas_width}x{canvas_height}')print(f'Text density: {text_cols}x{text_rows}')print(f'Elapsed time: {time.time() - since:.4} second(s)')代碼比較多,這里不做展示,需要的可以去下載。
python代碼實(shí)現(xiàn)把圖片生成字符畫(huà)(黑白色、彩色圖片)
總結(jié)
關(guān)于python代碼學(xué)習(xí)手把手教你將圖片變成字符畫(huà)(騷操作)就介紹到這了,上述實(shí)例對(duì)大家學(xué)習(xí)使用Python有一定的參考價(jià)值,希望大家閱讀完這篇文章能有所收獲。
總結(jié)
以上是生活随笔為你收集整理的python学习之手把手教你将图片变成黑白或彩色字符画(骚操作)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python爬取知乎热搜_python爬
- 下一篇: python打九九乘法表上三角下三角_p