アスキーアート変換プログラム
from LLMによるタスク管理
AA変換プログラム
https://gyazo.com/d5ff5c00b6296aa9825cc84555b16b9bhttps://gyazo.com/c412edb4eb8176e64993b8eaf7801d65
code:zsh
pip install pillow numpy
python img2ascii.py -i input.png -o out.txt -w 100 --invert
• -i/--input : 入力画像
• -o/--output: 出力テキスト(省略時は標準出力)
• -w/--width : 文字幅(既定: 80)
• --chars : 文字パレット(暗→明)。既定: “@%#*+=-:. “
• --invert : 明暗を反転(背景が暗い画像向け)
code:python
#!/usr/bin/env python3
import argparse
from PIL import Image
import numpy as np
import sys
DEFAULT_CHARS = "@%#*+=-:. "
def to_ascii(img_path, width=80, chars=DEFAULT_CHARS, invert=False):
# 1) 画像を開いてグレースケール
img = Image.open(img_path).convert("L")
# 2) アスペクト比補正してリサイズ
# 文字は縦長なので高さは0.5倍くらいにする
aspect_ratio = img.height / img.width
height = max(1, int(aspect_ratio * width * 0.5))
img_small = img.resize((width, height))
# 3) numpy配列にして明るさ→文字インデックスへ
arr = np.array(img_small, dtype=np.uint8)
if invert:
arr = 255 - arr
# 0..255 → 0..(len(chars)-1)
idx = (arr * (len(chars) - 1) // 255).astype(np.int32)
# 4) 行ごとに文字へ置換
lines = ["".join(charsi for i in row) for row in idx]
return "\n".join(lines)
def main():
p = argparse.ArgumentParser(description="Convert image to ASCII art.")
p.add_argument("-i", "--input", required=True, help="input image path")
p.add_argument("-o", "--output", help="output text file (default: stdout)")
p.add_argument("-w", "--width", type=int, default=80, help="output character width")
p.add_argument("--chars", default=DEFAULT_CHARS,
help=f'characters from dark->light (default: "{DEFAULT_CHARS}")')
p.add_argument("--invert", action="store_true", help="invert brightness mapping")
args = p.parse_args()
art = to_ascii(args.input, width=args.width, chars=args.chars, invert=args.invert)
if args.output:
with open(args.output, "w", encoding="utf-8") as f:
f.write(art)
else:
sys.stdout.write(art + "\n")
if __name__ == "__main__":
main()