我正在尝试将图像数据转换为可在控制台中打印的格式,该格式的颜色非常有限。 (这是在 python 3.12 中完成的)
我使用的颜色是基础红色、绿色、蓝色、黄色、青色、洋红色等。
我已经提取了 ANSI 颜色代码的 RGB 颜色,并且尝试比较将每个代码的三个值相加并获得差异的差异,但它不起作用,因为一个颜色通道可能使其看起来像另一种颜色到我的脚本,但实际上这是错误的频道。
一种常见的方法是通过从有限的 ANSI 调色板中查找与图像中每种 RGB 颜色最接近的匹配来量化颜色。这是一个使用 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
此代码将迭代图像中的每个像素,从预定义调色板中找到最接近的 ANSI 颜色,并使用这些有限的 ANSI 颜色创建图像的新表示形式