c# 查找相似颜色算法

时间:2025-03-15 07:48:41
using System; using System.Collections.Generic; public class ColorMatcher { // 颜色容器 - 使用字典存储颜色ID到RGB的映射 private readonly Dictionary<int, byte[]> _colorDictionary = new Dictionary<int, byte[]> { { 1, new byte[] { 255, 0, 0}}, { 2, new byte[] { 255, 255, 0}}, // ...此处省略其他颜色数据,实际使用时需完整填充 }; // 权重配置(可根据需要调整) private readonly double[] _channelWeights = new double[] { 1.0, 2.0, 1.0}; // R:1, G:2, B:1(亮度优先) /// <summary> /// 查找与目标颜色最相似的颜色ID /// </summary> /// <param name="targetColor">目标颜色RGB数组</param> /// <returns>最相似颜色ID</returns> public int FindClosestColor(byte[] targetColor) { if (targetColor == null || targetColor.Length != 3) throw new ArgumentException("Invalid color array"); double minDistance = double.MaxValue; int closestColorId = -1; foreach (var kvp