python学习之手把手教你将图片变成黑白或彩色字符画(骚操作)
文章目錄
- 前言
- 一、字符畫的實現原理
- 二、黑白字符畫實現代碼
- 三、彩色字符畫生成
- 代碼實現:
- 總結
前言
字符畫這個話題,似乎早在貼吧時代就已經被玩爛了。在百度圖片隨便一搜索,就能夠看到非常多。然后在這個時代,會編程的人越來越多(尤其是 MATLAB,Python 等非常適合圖像處理的腳本語言),類似的教程更是數不勝數。
一、字符畫的實現原理
字符畫是一系列字符的組合,我們可以把字符看作是比較大塊的像素,一個字符能表現一種顏色(暫且這么理解吧),字符的種類越多,可以表現的顏色也越多,圖片也會更有層次感。
問題來了,我們是要轉換一張彩色的圖片,這么多的顏色,要怎么對應到單色的字符畫上去?這里就要介紹灰度值的概念了。
灰度值:指黑白圖像中點的顏色深度,范圍一般從0到255,白色為255,黑色為0,故黑白圖片也稱灰度圖像
我們可以使用灰度值公式將像素的 RGB 值映射到灰度值:
gray = 0.2126 * r + 0.7152 * g + 0.0722 * b
這樣就好辦了,我們可以創建一個不重復的字符列表,灰度值小(暗)的用列表開頭的符號,灰度值大(亮)的用列表末尾的符號。
二、黑白字符畫實現代碼
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') # 需要設置輸入文件parser.add_argument('-o', '--output') # 輸出文件parser.add_argument('--width', type=int, default=80) # 輸出字符畫寬parser.add_argument('--height', type=int, default=80) # 輸出字符畫高# 獲取參數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)#字符畫輸出到文件if OUTPUT:with open(OUTPUT,'w') as f:f.write(txt)else:with open("output.txt",'w') as f:f.write(txt)三、彩色字符畫生成
代碼實現:
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代碼實現把圖片生成字符畫(黑白色、彩色圖片)
總結
關于python代碼學習手把手教你將圖片變成字符畫(騷操作)就介紹到這了,上述實例對大家學習使用Python有一定的參考價值,希望大家閱讀完這篇文章能有所收獲。
總結
以上是生活随笔為你收集整理的python学习之手把手教你将图片变成黑白或彩色字符画(骚操作)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python爬取知乎热搜_python爬
- 下一篇: Ubuntu中程序崩溃,杀死进程方法