The code for this is in python and goes as follows
from PIL import Imagefrom rich.console import Consolefrom rich.text import Textfrom cv2 import imwrite, VideoCapturefrom os import system, name# Function to map pixels to ASCII charactersdef pixel_to_ascii(pixel, ascii_chars): return ascii_chars[pixel * len(ascii_chars) // 256]# Function to convert image to colored ASCIIdef image_to_ascii_with_color(image_path, new_width=100): ASCII_CHARS = ["█"] # Open the image image = Image.open(image_path) # Resize the image maintaining the aspect ratio width, height = image.size aspect_ratio = height / width new_height = int(aspect_ratio * new_width * 0.4) image = image.resize((new_width, new_height)) # Convert the image to grayscale gray_image = image.convert("L") # Get pixel data pixels = gray_image.getdata() color_pixels = image.getdata() # Create ASCII art ascii_str = "".join(pixel_to_ascii(p, ASCII_CHARS) for p in pixels) # Split ASCII string into lines lines = [ascii_str[i:i + new_width] for i in range(0, len(ascii_str), new_width)] # Print colored ASCII art using rich console = Console() for y, line in enumerate(lines): rich_text = Text() for x, char in enumerate(line): index = y * new_width + x if index < len(color_pixels): r, g, b = color_pixels[index] rich_text.append(char, style=f"rgb({r},{g},{b})") console.print(rich_text)# Function to capture photo from webcamdef capture_photo(filename='1.jpg'): cap = VideoCapture(0) if not cap.isOpened(): print("Error: Could not open webcam.") return False ret, frame = cap.read() cap.release() if not ret: print("Error: Could not read frame.") return False imwrite(filename, frame) return True# Main functiondef main(): while True: if capture_photo(): system('cls' if name == 'nt' else 'clear') image_to_ascii_with_color('image.jpg')if __name__ == "__main__": main()Whenever I run it it is very slow and sometimes starts to lag and make artifacts on the image making it look horrible. It will work fine at the start but the more it runs the more it lags and causes artifacts. The artifacts I'm talking about are miscolored pixels spreading through the canvas.
I have tried to use functools @cache and have not found a way to optimize it or get rid of the artifacts. I don't know if the problem can be fixed or if it is the rich library's fault but if someone could help that would be great. Also if someone could test for the artifacts in their terminal it would be appreciated. Please help me figure out this optimization and 'rich' library mystery. BTW I'm using vscode if anyone thinks that the problem.