Created
March 3, 2025 20:35
-
-
Save Jpoliachik/6992799d3c3d96166dba3c3e5a5465fe to your computer and use it in GitHub Desktop.
Revisions
-
Jpoliachik revised this gist
Mar 3, 2025 . No changes.There are no files selected for viewing
-
Jpoliachik revised this gist
Mar 3, 2025 . No changes.There are no files selected for viewing
-
Jpoliachik created this gist
Mar 3, 2025 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,61 @@ import PIL.Image import numpy as np def image_to_ascii(image_path, output_path, ascii_char='#', width=100): """ Convert a black and white image to ASCII art using a single character Args: image_path: Path to the input image output_path: Path to save the ASCII art as text file ascii_char: Character to use for the ASCII art width: Width of the ASCII art in characters """ # Open image and convert to grayscale img = PIL.Image.open(image_path).convert('L') # Calculate new height to maintain aspect ratio aspect_ratio = img.height / img.width height = int(width * aspect_ratio * 0.43) # Font-specific adjustment factor # Resize image img = img.resize((width, height)) # Convert to numpy array for easier processing pixels = np.array(img) # Create ASCII art with fixed-width formatting ascii_art = [] for row in pixels: line = '' for pixel in row: # Use ascii_char for dark pixels, space for light pixels if pixel < 128: # Threshold at middle gray value line += ascii_char else: line += ' ' # Ensure each line is exactly the same width by padding with spaces line = line.ljust(width) ascii_art.append(line) # Join lines and write to file ascii_text = '\n'.join(ascii_art) # Write to text file with open(output_path, 'w') as f: f.write(ascii_text) print(f"ASCII art saved to {output_path}") # Example usage if __name__ == "__main__": import sys if len(sys.argv) >= 2: input_image = sys.argv[1] output_file = sys.argv[2] if len(sys.argv) >= 3 else "ascii_art.txt" char = sys.argv[3] if len(sys.argv) >= 4 else "#" width = int(sys.argv[4]) if len(sys.argv) >= 5 else 100 image_to_ascii(input_image, output_file, char, width) else: print("Usage: python script.py input_image [output_file] [ascii_char] [width]")