บทความนี้จะแสดงวิธีแปลงภาพ (Image) ให้กลายเป็น ASCII Art คือภาพที่ประกอบด้วยตัวอักษร ASCII ต่างๆ แทนสีและเงา
หลักการทำงาน
- เปิดภาพด้วย
PIL (Pillow) - ปรับขนาดภาพ (Resize) ให้เหมาะสม
- แปลงเป็น Grayscale (ขาว-ดำ)
- แมปค่าความสว่างของพิกเซลแต่ละจุดเป็นตัวอักษร ASCII ที่เหมาะสม
- จัดรูปแบบให้เป็นบรรทัด-คอลัมน์ แล้วบันทึกเป็นไฟล์ข้อความ
โปรแกรมเต็ม
from PIL import Image
import os
ASCII_CHARS = ['#', '?', '%', '.', 'S', '+', '.', '*', ':', ',', '@']
def resize_image(image, new_width=25):
width, height = image.size
aspect_ratio = height / float(width)
new_height = int(aspect_ratio * new_width)
return image.resize((new_width, new_height))
def make_grey(image):
return image.convert('L')
def pixel_to_ascii(image, range_width=25):
pixels = list(image.getdata())
chars = [ASCII_CHARS[pixel_value // range_width] for pixel_value in pixels]
return "".join(chars)
def image_to_ascii(image, new_width=25):
image = resize_image(image)
image = make_grey(image)
chars = pixel_to_ascii(image)
lines = [chars[index: index + new_width] for index in range(0, len(chars), new_width)]
return "\n".join(lines)
def convert_image(image_filepath):
try:
image = Image.open(image_filepath)
except Exception as e:
print(f"Unable to open image file {image_filepath}.")
print(e)
return
image_ascii = image_to_ascii(image)
output_path = os.path.splitext(image_filepath)[0] + '.txt'
with open(output_path, 'w') as f:
f.write(image_ascii)
convert_image('D:\\button.jpg')
ผลลัพธ์
ภาพต้นฉบับ

ASCII Art ผลลัพธ์

การปรับแต่ง: สามารถเปลี่ยน ASCII_CHARS ให้มีตัวอักษรมากขึ้น เพื่อให้รายละเอียดมากขึ้น หรือปรับ new_width ให้ใหญ่ขึ้น
ติดตั้ง Pillow: pip install pillow