用python写一个程序。输入一幅图片,然后仅使用ascii字符尽可能高质量地重绘图片,并将结果保存为文本文件
- User
用python写一个程序。输入一幅图片,然后仅使用ascii字符尽可能高质量地重绘图片,并将结果保存为文本文件
Assistant
以下是一个使用Python将图像转换为高质量ASCII艺术的程序。该程序使用灰度映射和字符密度优化来提升视觉效果,并支持调整输出尺寸。
from PIL import Image import argparse import numpy as np def main(): # 解析命令行参数 parser = argparse.ArgumentParser(description='Convert image to ASCII art') parser.add_argument('image_path', type=str, help='Path to input image') parser.add_argument('--output', type=str, default='output.txt', help='Output text file path') parser.add_argument('--width', type=int, default=100, help='Width of ASCII output (in characters)') parser.add_argument('--invert', action='store_true', help='Invert colors for dark backgrounds') args = parser.parse_args() try: # 打开并预处理图像 img = Image.open(args.image_path) img = preprocess_image(img, args.width) # 转换为ASCII并保存 ascii_art = image_to_ascii(img, args.invert) with open(args.output, 'w', encoding='utf-8') as f: f.write(ascii_art) print(f"ASCII art saved to {args.output}") except Exception as e: print(f"Error: {str(e)}") def preprocess_image(img, target_width): """调整图像尺寸并转换为灰度图""" aspect_ratio = img.height / img.width new_height = int(aspect_ratio * target_width * 0.55) # 补偿字符高宽比 img = img.convert('L').resize((target_width, new_height)) return img def image_to_ascii(img, invert=False): """将灰度图像转换为ASCII字符串""" # 按视觉密度排序的ASCII字符集(从暗到亮) charsets = [ '@%#*+=-:. ', # 标准 '$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,"^`\'. ', # 详细 '@WMBRXVYbduoa*+~-:.` ' # 中等 ] chars = charsets[1] # 选择详细字符集以获得高质量 if invert: chars = chars[::-1] # 反转字符集 # 将像素值映射到字符索引 pixels = np.array(img) min_val, max_val = pixels.min(), pixels.max() if max_val == min_val: scaled = np.zeros_like(pixels) else: scaled = (pixels - min_val) / (max_val - min_val) # 创建ASCII艺术 ascii_str = "" for row in scaled: line = ''.join(chars[min(int(val * (len(chars) - 1)), len(chars) - 1)] for val in row) ascii_str += line + '\n' return ascii_str if __name__ == "__main__": main()使用说明:
-
安装依赖:
pip install pillow numpy -
运行程序:
python ascii_art.py input_image.jpg --output result.txt --width 120
参数说明:
image_path: 输入图像路径(必需)--output: 输出文本文件路径(默认:output.txt)--width: ASCII艺术宽度(字符数,默认:100)--invert: 反转颜色(适用于深色背景)
优化特点:
-
智能字符映射:
- 使用视觉密度优化的字符集(70级灰度)
- 自动对比度拉伸增强细节
- 支持颜色反转选项
-
比例补偿:
- 自动调整高度(补偿终端字符的高宽比)
- 保持原始图像比例
-
高质量输出:
- 使用详细字符集保留更多细节
- 多种字符集可选(代码中可切换)
效果提升技巧:
- 对于简单图像:使用
charsets[0] - 对于复杂图像:使用
charsets[1](默认) - 终端显示时:使用小字号和深色背景
- 最佳宽度:80-150字符(根据图像复杂度调整)
示例输出(使用默认字符集):
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@%*+=====+***#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@%+-.` `.-+#%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@%*-` `-+%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@#-` .-*%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@%=` :#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@#. -%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@%: +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@* =@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@此程序在保留图像细节和保持可读性之间取得了良好平衡,通过选择合适的字符集和宽度参数,可以适应各种类型的图像。
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.