Search code examples
pythoncolorsrgb

How do I convert RGB values to the closest ANSI color code?


I'm trying to convert image data into a format printable in a console, which has very limited colors. (This is being done in python 3.12)

The colors that I'm using are the base red, green, blue, yellow, cyan, magenta etc.

I have already extracted the RGB colors for the ANSI color codes and I tried to compare the differences of adding the three values together for each code and getting the difference but it didn't work as one colour channel could make it look like another colour to my script, but in actuality it was the wrong channel.


Solution

  • One common approach is to quantize the colors by finding the closest match from your limited ANSI color palette to each RGB color in the image. Here's a simplified example using Python:

    # Your ANSI color palette in RGB
    ansi_colors = {
        'red': (255, 0, 0),
        'green': (0, 255, 0),
        'blue': (0, 0, 255),
        # Add other ANSI colors and their RGB values
    }
    
    # Your image data in RGB format (example)
    image_data = [
        [(255, 120, 50), (30, 200, 100), ...],  # Replace with your image data
        # Add more rows of pixels
    ]
    
    def find_closest_color(rgb_color):
        min_distance = float('inf')
        closest_color = None
        for ansi_color, ansi_rgb in ansi_colors.items():
            # Calculate Euclidean distance between RGB colors
            distance = sum((c1 - c2) ** 2 for c1, c2 in zip(rgb_color, ansi_rgb))
            if distance < min_distance:
                min_distance = distance
                closest_color = ansi_color
        return closest_color
    
    # Convert image data to ANSI color codes
    ansi_image = []
    for row in image_data:
        ansi_row = []
        for pixel in row:
            closest = find_closest_color(pixel)
            ansi_row.append(closest)
        ansi_image.append(ansi_row)
    
    # Print ANSI color codes in console
    for row in ansi_image:
        for pixel in row:
            print(pixel, end=' ')
        print()  # Move to the next line for the next row
    

    This code will iterate through each pixel in the image, find the closest ANSI color from your predefined palette, and create a new representation of the image using these limited ANSI colors