Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

파이썬(Python)으로 이미지를 ASCII 아트로 변환하는 방법

이 글에서는 주어진 이미지를 텍스트 기반 이미지, 즉 ASCII 아트(ASCII Art)로 변환하는 방법을 살펴봅니다.

아래의 파이썬 프로그램은 입력 이미지를 받아 여러 단계의 함수를 통해 회색조(grayscale) 이미지로 변환한 뒤, 픽셀의 밝기 값에 따라 ASCII 문자를 매핑하여 다양한 패턴을 만들어냅니다. 최종 결과물은 일련의 일반 ASCII 문자로만 구성된 텍스트 기반 이미지입니다.

변환 과정의 핵심 단계

전체 변환 과정은 크게 세 단계로 나눌 수 있습니다.

  • 이미지 크기 조정: 가로세로 비율(aspect ratio)을 유지하면서 이미지를 지정된 너비(기본값 25픽셀)로 축소합니다.
  • 회색조 변환: PIL의 convert('L') 메서드를 사용해 이미지를 흑백으로 바꿉니다.
  • 픽셀-ASCII 매핑: 각 픽셀의 밝기 값을 ASCII 문자 목록의 인덱스로 활용해 해당 문자로 치환합니다.

예제 코드

from PIL import Image
import os

ASCII_CHARS = ['#', '?', '%', '.', 'S', '+', '.', '*', ':', ',', '@']

def resize_image(image, new_width=25):
    (input__width, input__height) = image.size
    aspect_ratio = input__height / float(input__width)
    changed_height = int(aspect_ratio * new_width)
    changed_image = image.resize((new_width, changed_height))
    return changed_image

def make_grey(image):
    return image.convert('L')

def pixel_to_ascii(image, range_width=25):
    pixels_in_image = list(image.getdata())
    pixels_to_chars = [ASCII_CHARS[pixel_value // range_width] for pixel_value in pixels_in_image]
    return "".join(pixels_to_chars)

def image_to_ascii(image, new_width=25):
    image = resize_image(image)
    image = make_grey(image)
    pixels_to_chars = pixel_to_ascii(image)
    len_pixels_to_chars = len(pixels_to_chars)
    image_ascii = [pixels_to_chars[index: index + new_width] for index in range(0, len_pixels_to_chars, new_width)]
    return "\n".join(image_ascii)

def convert_image(image_filepath):
    try:
        image = Image.open(image_filepath)
    except Exception as e:
        print("Unable to open image file {image_filepath}.".format(image_filepath=image_filepath))
        print(e)
        return
    image_ascii = image_to_ascii(image)
    f = open(os.path.splitext(image_filepath)[0] + '.txt', 'w')
    f.write(image_ascii)
    f.close()

convert_image('D:\\button.jpg')

주요 함수 설명

  • resize_image(): 원본 이미지의 종횡비를 계산해 새로운 너비에 맞춰 크기를 조정합니다.
  • make_grey(): 이미지를 8비트 회색조 모드로 변환합니다.
  • pixel_to_ascii(): 이미지의 모든 픽셀 값을 읽어 범위 폭(range_width)으로 나눈 뒤, 그 몫을 인덱스로 ASCII 문자를 선택하고 하나의 문자열로 연결합니다.
  • image_to_ascii(): 앞선 함수들을 순서대로 호출한 후, 문자열을 지정된 너비만큼 잘라 줄바꿈 문자로 연결해 최종 ASCII 아트를 완성합니다.
  • convert_image(): 이미지 파일을 열고 변환을 수행한 뒤, 결과를 원본 파일명과 동일한 이름의 .txt 파일로 저장합니다.

실행 결과

위 코드를 실행하면 다음과 같은 결과를 얻을 수 있습니다.

입력 이미지

파이썬(Python)으로 이미지를 ASCII 아트로 변환하는 방법

출력 이미지(ASCII 아트)

파이썬(Python)으로 이미지를 ASCII 아트로 변환하는 방법