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)
浙公網安備 33010602011771號