用python写一个程序。输入一幅图片,然后仅使用ascii字符尽可能高质量地重绘图片,并将结果保存为文本文件
- User
用python写一个程序。输入一幅图片,然后仅使用ascii字符尽可能高质量地重绘图片,并将结果保存为文本文件
Assistant
以下是一个Python程序,可以将图片转换为ASCII艺术并保存为文本文件:
from PIL import Image import numpy as np def image_to_ascii(image_path, output_path, width=100, height=None): # 加载图片 img = Image.open(image_path) # 调整图片大小 if height is None: # 保持宽高比 aspect_ratio = img.height / img.width height = int(width * aspect_ratio * 0.5) # 乘0.5是因为字符在终端中高宽比约为2:1 img = img.resize((width, height)) # 转换为灰度图 img = img.convert('L') # ASCII字符集,从暗到亮 ascii_chars = '@%#*+=-:. ' # 将像素值映射到ASCII字符 pixels = np.array(img) ascii_image = [] for row in pixels: ascii_row = '' for pixel in row: # 将0-255的像素值映射到ASCII字符集的索引 index = int(pixel * len(ascii_chars) / 256) ascii_row += ascii_chars[index] ascii_image.append(ascii_row) # 将ASCII艺术保存到文本文件 with open(output_path, 'w', encoding='utf-8') as f: f.write('\n'.join(ascii_image)) print(f"ASCII艺术已保存到 {output_path}") if __name__ == "__main__": # 获取用户输入 image_path = input("请输入图片路径: ") output_path = input("请输入输出文本文件路径: ") width = int(input("请输入ASCII艺术的宽度(字符数): ") or "100") # 转换图片为ASCII艺术 image_to_ascii(image_path, output_path, width)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.