from PIL import Image
import argparse
#命令列輸入引數處理
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.file
WIDTH = args.width
HEIGHT = args.height
OUTPUT = args.output
def strB2Q(ustring):
"""半形轉全形"""
rstring = ""
for uchar in ustring:
inside_code=ord(uchar)
if inside_code == 32: #半形空格直接轉化
inside_code = 12288
elif inside_code >= 32 and inside_code <= 126: #半形字元(除空格)根據關係轉化
inside_code += 65248
rstring += chr(inside_code)
return rstring
ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
# 將256灰度對映到70個字元上
def get_char(r,b,g,alpha = 256):
# 白色返回空
if alpha == 0:
return ' '
length = len(ascii_char)
#灰度值公式
gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
#因為70個字元的陣列下標範圍是從0到69,如果不加1,灰度為256時會取下標為70,此時超出陣列範圍
unit = (256.0 + 1)/length
return ascii_char[int(gray/unit)]
if __name__ == '__main__':
#載入IMG的檔案
im = Image.open(IMG)
#重置或預設值
HEIGHT=int(WIDTH*im.size[1]/im.size[0]*0.55)
im = im.resize((WIDTH,HEIGHT), Image.NEAREST)
txt = ""
for i in range(HEIGHT):
for j in range(WIDTH):
#返回指定位置的畫素
txt += get_char(*im.getpixel((j,i)))
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)
參考連結:圖片轉字元畫 https://gitee.com/wangyufu/python-ASCII-Generator/blob/master/ascii.py
Python 圖片轉字元畫 https://www.cnblogs.com/wangyufu/p/5602848.html
from PIL import Image
import numpy as np
# 定義字符集,從暗到亮
ASCII_CHARS = "@%#*+=-:. "
def resize_image(image, new_width=100):
(original_width, original_height) = image.size
aspect_ratio = original_height / float(original_width)
new_height = int(aspect_ratio * new_width * 0.55) # 0.55是為了補償字元高度
resized_image = image.resize((new_width, new_height))
return resized_image
def grayify(image):
return image.convert("L") # 轉換為灰度圖
def pixels_to_ascii(image):
pixels = np.array(image)
ascii_str = ""
for pixel_value in pixels:
for pv in pixel_value.tolist():
ascii_str += ASCII_CHARS[pv // 25] # 將畫素值對映到字符集
return ascii_str
def convert_image_to_ascii(image_path, new_width=100):
try:
image = Image.open(image_path)
except Exception as e:
print(e)
return
image = resize_image(image, new_width)
image = grayify(image)
ascii_str = pixels_to_ascii(image)
img_width = image.width
ascii_str_len = len(ascii_str)
ascii_img = ""
# 將長字串分割為行
for i in range(0, ascii_str_len, img_width):
ascii_img += ascii_str[i:i + img_width] + "\n"
return ascii_img
# 使用示例
if __name__ == "__main__":
image_path = "test.jpg" # 替換為你的圖片路徑
ascii_image = convert_image_to_ascii(image_path, new_width=100)
print(ascii_image)
# 如果需要將結果儲存到檔案中
with open("ascii_image.txt", "w") as f:
f.write(ascii_image)