Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import numpy as np
- from PIL import Image, ImageDraw
- from tensorflow import keras
- characters = "abcdefghijklmnopqrstuvwxyz"
- num_classes = len(characters)
- ascii_art_folder = "dataset"
- image_folder = "images"
- for character in characters:
- ascii_file = os.path.join(ascii_art_folder, character + ".txt")
- image_file = os.path.join(image_folder, character + ".png")
- with open(ascii_file, "r") as file:
- ascii_art = file.read()
- image = Image.new("RGB", (100, 100), color="white")
- image_draw = ImageDraw.Draw(image)
- image_draw.text((10, 10), ascii_art, fill="black")
- image.save(image_file)
- samples = []
- labels = []
- for character in characters:
- image_file = os.path.join(image_folder, character + ".png")
- image = Image.open(image_file).convert("L")
- image = image.resize((64, 64))
- image_array = np.array(image)
- image_array = image_array / 255.0
- samples.append(image_array)
- labels.append(characters.index(character))
- samples = np.array(samples)
- labels = np.array(labels)
- # Split the dataset into training and testing
- split_ratio = 0.8
- split_index = int(len(samples) * split_ratio)
- train_samples = samples[:split_index]
- train_labels = labels[:split_index]
- test_samples = samples[split_index:]
- test_labels = labels[split_index:]
- # Define the model architecture
- model = keras.models.Sequential([
- keras.layers.Conv2D(32, (3, 3), activation="relu", input_shape=(64, 64, 1)),
- keras.layers.MaxPooling2D((2, 2)),
- keras.layers.Flatten(),
- keras.layers.Dense(64, activation="relu"),
- keras.layers.Dense(num_classes, activation="softmax")
- ])
- # Compile the model
- model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])
- # Train the model
- model.fit(train_samples, train_labels, epochs=100, batch_size=32, validation_split=0.2)
- # Evaluate the model
- test_loss, test_acc = model.evaluate(test_samples, test_labels)
- print(f"Test accuracy: {test_acc}")
- # Convert input ASCII art to image and predict the letter
- input_ascii_art = """
- _ _
- | | | |
- | |_| |
- \__, |
- |___/
- """
- input_image = Image.new("RGB", (100, 100), color="white")
- input_image_draw = ImageDraw.Draw(input_image)
- input_image_draw.text((10, 10), input_ascii_art, fill="black")
- input_image = input_image.convert("L")
- input_image = input_image.resize((64, 64))
- input_image_array = np.array(input_image) / 255.0
- input_image_array = np.expand_dims(input_image_array, axis=0)
- input_image_array = np.expand_dims(input_image_array, axis=-1)
- prediction = model.predict(input_image_array)
- predicted_index = np.argmax(prediction)
- predicted_character = characters[predicted_index]
- print(f"Predicted character: {predicted_character}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement