Project-3

Project-3

Project 3 is a project in Python because why not. I saw an image processing sequence on GitHub .Then I wanted to try it myself.

So, I wrote a Python script that converts an image into an ASCII representation using a predefined set of characters. The program processes the image by resizing it, converting it to grayscale, and then mapping different shades of gray to specific characters from the chosen set. This way, the final output resembles the original image but is composed entirely of text characters.

The Code:

from PIL import Image, ImageDraw, ImageFont
import math
chars = "$@B%8&WM#*/F\L\O|W()oahkbdpqwmZO0QLCJUYXzcvunxrjft1{}[]?-_+~<>i!lI;:,\"^`'. "[::-1]# chars = "#Wo- "[::-1]  1 )$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/F\L\O|W()1{}[]?-_+~<>i!lI;:,\"^`'. "[::-1]#    x    x               1.5 )/f\l\o|w()1{}[]?-_+~<>i!lI;:,\"^`'. "[::-1]#    x    x               1.5 )/f\l\o|w()1{}[]?-_+~<>i!lI;:,\"^`'. "[::-1]#    x    x               1.5 )/f\l\o|w()1{}[]?-_+~<>i!lI;:,\"^`'. "[::-1]#    x    x               1.5 )/f\l\o|w()1{}[]?-_+~<>i!lI;:,\"^`'. "[::-1]#    x    x               1.5 )/f\l\o|w()1{}[]?-_+~<>i!lI;:,\"^`'. "[::-1]charArray = list(chars)charLength = len(charArray)interval = charLength/256
scaleFactor = 0.09
oneCharWidth = 10oneCharHeight = 18
def getChar(inputInt):    return charArray[math.floor(inputInt*interval)]
text_file = open("Output.txt", "w")
im = Image.open("DSCYB2nebo4.jpg")
fnt = ImageFont.truetype('C:\\Windows\\Fonts\\lucon.ttf', 15)
width, height = im.sizeim = im.resize((int(scaleFactor*width), int(scaleFactor*height*(oneCharWidth/oneCharHeight))), Image.NEAREST)width, height = im.sizepix = im.load()
outputImage = Image.new('RGB', (oneCharWidth * width, oneCharHeight * height), color = (0, 0, 0))d = ImageDraw.Draw(outputImage)
for i in range(height):    for j in range(width):        r, g, b = pix[j, i]        h = int(r/3 + g/3 + b/3)        pix[j, i] = (h, h, h)        text_file.write(getChar(h))        d.text((j*oneCharWidth, i*oneCharHeight), getChar(h), font = fnt, fill = (r, g, b))
    text_file.write('\n')
outputImage.save('output.png')

📌 What does this code do?
✅ Loads an image.
✅ Resizes it for ASCII representation.
✅ Converts each pixel to a corresponding ASCII character based on its brightness.
✅ Saves the ASCII text to Output.txt.
✅ Creates an output image (output.png) with ASCII characters as an overlay.

📌 What could be improved?
🔹 Use more advanced character mapping (better distinction between light and dark areas).
🔹 Add an option to select the input file via script arguments.
🔹 Optimize performance (e.g., use vectorization with NumPy).