This commit is contained in:
Achille 2024-07-05 16:38:56 +02:00
parent e9769cba16
commit 12f0c5ae93
2 changed files with 31 additions and 13 deletions

View file

Before

Width:  |  Height:  |  Size: 70 KiB

After

Width:  |  Height:  |  Size: 70 KiB

Before After
Before After

44
main.py
View file

@ -1,10 +1,9 @@
from PIL import Image, ImageDraw, ImageFont
from PIL import Image, ImageDraw, ImageFont, ImageFilter, ImageChops
import numpy as np
import os
def imageToAsciiText(path, cell_size=(8, 8)):
image = Image.open(path)
image = image.convert('L') # Convert to grayscale
width, height = image.size
pixels = np.array(image)
asciiCharacters = "@%#*+=-:. " # From darkest to lightest
@ -49,36 +48,55 @@ def asciiTextToImage(asciiText, fontPath, cellSize, fontSize, clarityFactor):
return image
def applySobelFilter(image):
# Convert the image to grayscale
grayImage = image.convert('L')
# Apply the Sobel filter
sobelX = grayImage.filter(ImageFilter.FIND_EDGES)
sobelY = grayImage.filter(ImageFilter.FIND_EDGES).rotate(90)
# Combine the horizontal and vertical edges
sobelImage = ImageChops.add(sobelX, sobelY)
return sobelImage
# Get the current directory
currentDir = os.path.dirname(os.path.abspath(__file__))
# Create the export directory if it doesn't exist
exportDir = os.path.join(currentDir, "output")
os.makedirs(exportDir, exist_ok=True)
outputDir = os.path.join(currentDir, "output")
os.makedirs(outputDir, exist_ok=True)
# Edit params
cellSize = (8, 8)
# Parameters
cellSize = (32, 32)
fontPath = 'fonts/courbd.ttf' # Specify the path to your font file
fontSize = 10 # font size in points
fontSize = cellSize[0] * 1.2 # font size in points
clarityFactor = 8 # Increase this value to improve the clarity of the ASCII art
# Process all images in the current directory
for filename in os.listdir(currentDir):
inputDir = os.path.join(currentDir, "input")
for filename in os.listdir(inputDir):
if filename.endswith(".jpg") or filename.endswith(".png"):
# Construct the full path of the image
imagePath = os.path.join(currentDir, filename)
imagePath = os.path.join(inputDir, filename)
# Generate the output file name
outputFilename = os.path.splitext(filename)[0] + "_asciiart.jpg"
outputPath = os.path.join(exportDir, outputFilename)
outputPath = os.path.join(outputDir, outputFilename)
# Load the image into a PIL image object and apply filters
image = Image.open(imagePath)
image = image.convert('L') # Convert to grayscale
# Call the imageToAsciiText function and save the result to the output file
asciiText = imageToAsciiText(imagePath, cellSize)
asciiText = imageToAsciiText(image, cellSize)
asciiImage = asciiTextToImage(asciiText, fontPath, int(cellSize[0]), fontSize, clarityFactor)
asciiImage.save(outputPath)
# Print the output file path
print(f"Processed image: {outputPath}")