2023-10-10 python-从一组颜色中找到与指定颜色最接近的颜色-{K-D树}-记录

摘要:

2023-10-10 python-从一组颜色中找到与指定颜色最接近的颜色-{K-D树}-记录

相关文档:

如何在颜色表中找到与当前颜色最接近的颜色? - 糯米PHP

https://zh.wikipedia.org/wiki/%E6%9C%80%E9%82%BB%E8%BF%91%E6%90%9C%E7%B4%A2

https://zh.wikipedia.org/wiki/K-d%E6%A0%91

K-D树算法:

import numpy as np  
from scipy.spatial import KDTree  
  

"""  
在颜色列表中找到与目标颜色最接近的颜色。  

参数:  
    target_color (tuple): 目标颜色, 如 (255, 0, 0) 表示红色.  
    color_list (list): 所有颜色的列表, 如 [(r1, g1, b1), (r2, g2, b2), ...].  

返回:  
    tuple: 最接近目标颜色的颜色.  
"""  
def find_closest_color(target_color, color_list):  
    # 将RGB颜色转换为浮点数数组  
    colors = np.array(color_list)  
    colors_float = colors.astype(float)  
  
    # 创建k-d树  
    kdtree = KDTree(colors_float)  
  
    # 找到目标颜色的最近邻  
    dist, idx = kdtree.query([target_color])  
  
    # 返回最近邻颜色  
    return color_list[idx[0]]  
  

color_list = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (0, 255, 255)]  
target_color = (255, 255, 0)  

closest_color = find_closest_color(target_color, color_list)  
print("Closest color to target is", closest_color)  


你可能感兴趣的:(python,python,开发语言,K-D树)