কম্পিউটার টিউটোরিয়াল

পাইথনে ইমেজকে ASCII ইমেজে রূপান্তর

এই আর্টিকেলে আমরা একটি দেয়া ইমেজকে টেক্সট-ভিত্তিক ইমেজ বা ASCII ইমেজে রূপান্তর করতে চাই।

নিচে পাইথন প্রোগ্রামটি দেওয়া হলো যা একটি ইনপুট ইমেজ নেবে এবং বিভিন্ন ফাংশন ব্যবহার করে সেটাকে গ্রে-স্কেল পিকচারে রূপান্তর করবে এবং তারপর 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')

আউটপুট

উপরের কোডটি রান করলে নিচের ফলাফলটি মিলবে −

ইনপুট ইমেজ

পাইথনে ইমেজকে ASCII ইমেজে রূপান্তর

আউটপুট ইমেজ

পাইথনে ইমেজকে ASCII ইমেজে রূপান্তর

  1. পাইথনে কনভোলিউশন (Convolutions) ব্যবহার

  2. পাইথনে ছবি পড়া (OpenCV এবং PIL ব্যবহার করে)

  3. পাইথনে ফোটোমোজেইক ইমপ্লিমেন্টেশন (Photomosaics)

  4. পাইথনে SunPy ব্যবহার করে সৌর ছবি প্লট করা