from PIL import Image from collections import Counter import numpy as np def save_colors_to_file(image_path, output_file): # 打开图片文件 image = Image.open(image_path) image = image.convert('RGB') # 将图片转换为numpy数组 pixels = np.array(image) # 获取所有颜色的RGB值,并转换为元组形式,以便可以作为字典的键 colors = [tuple(pixel) for pixel in pixels.reshape(-1, 3)] # 使用Counter统计每种颜色的出现次数 color_counts = Counter(colors) # 按照出现次数从大到小排序颜色 sorted_colors = sorted(color_counts.items(), key=lambda x: x[1], reverse=True) # 将RGB颜色转换为HEX颜色 hex_colors = [(f'#{int(r):02x}{int(g):02x}{int(b):02x}', count) for (r, g, b), count in sorted_colors] # 打开文件并写入颜色信息 with open(output_file, 'w') as file: for hex_color, count in hex_colors: file.write(f'HEX: {hex_color}, Count: {count}\n') # 使用示例 image_path = r'C:\壁纸\1.jpg' # 替换为你的图片路径 output_file = 'colors_output.txt' # 输出文件的路径 save_colors_to_file(image_path, output_file)
标签:颜色,python,image,color,colors,file,output,列出 From: https://www.cnblogs.com/jingzaixin/p/18416536