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)
2.占整体的百分比:
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) # 计算总像素数 total_pixels = len(pixels) # 将RGB颜色转换为HEX颜色,并计算占比 hex_colors_with_info = [] for (r, g, b), count in sorted_colors: hex_color = f'#{int(r):02x}{int(g):02x}{int(b):02x}' percentage = (count / total_pixels) * 100 hex_colors_with_info.append((hex_color, percentage)) # 打开文件并写入颜色信息 with open(output_file, 'w', encoding='utf-8') as file: for hex_color, percentage in hex_colors_with_info: file.write(f'HEX: {hex_color}, 占比: {percentage:.2f}%\n') # 使用示例 image_path = r'C:\壁纸\1.jpg' # 替换为你的图片路径 output_file = 'colors_output_with_percentages.txt' # 输出文件的路径 save_colors_to_file(image_path, output_file)