【问题标题】:Finding which color is the closest to the given RGB values in C在 C 中查找最接近给定 RGB 值的颜色
【发布时间】:2017-10-26 15:14:59
【问题描述】:

这是一个包含 20 种最简单、最独特的颜色的网站:http://sashat.me/2017/01/11/list-of-20-simple-distinct-colors/

我正在制作一个检测颜色并给它们命名的程序。

问题是我需要一个函数:

  • 采用 3 个参数,R、G 和 B。

  • 在给定 RGB 函数时,确定 20 种颜色中的哪种颜色最接近。

下面是一些理想函数的例子:

[127,2,1] -> Outputs Maroon
[245,7,6] -> Outputs Red
[7,235,0] -> Outputs Green

任何关于如何制作这样的东西的帮助将不胜感激!谢谢!

【问题讨论】:

  • 我不是专家,但可能取最接近差异总和或差异平方和的值?
  • 没有明确的答案 - 尝试创建感知上一致的色彩空间会让您很快陷入深渊。但是 5 倍的红色差异、9 倍的绿色差异和 2 倍的蓝色差异是一个好的开始。
  • @HansPassant 我知道了,谢谢。

标签: c arrays colors rgb


【解决方案1】:

为了帮助未来的观众,我已经回答了自己的问题。

使用维基百科上找到并显示在 cmets 中的色差公式,此函数将接受 3 个参数并返回最接近的颜色。

const int distinctRGB[22][3] = {{255, 255, 255},{0,0,0},{128,0,0},{255,0,0},{255, 200, 220},{170, 110, 40},{255, 150, 0},{255, 215, 180},{128, 128, 0},{255, 235, 0},{255, 250, 200},{190, 255, 0},{0, 190, 0},{170, 255, 195},{0, 0, 128},{100, 255, 255},{0, 0, 128},{67, 133, 255},{130, 0, 150},{230, 190, 255},{255, 0, 255},{128, 128, 128}};
const String distinctColors[22] = {"white","black","maroon","red","pink","brown","orange","coral","olive","yellow","beige","lime","green","mint","teal","cyan","navy","blue","purple","lavender","magenta","grey"};
String closestColor(int r,int g,int b) {
  String colorReturn = "NA";
  int biggestDifference = 1000;
  for (int i = 0; i < 22; i++) {
    if (sqrt(pow(r - distinctRGB[i][0],2) + pow(g - distinctRGB[i][1],2) + pow(b - distinctRGB[i][2],2)) < biggestDifference) {
      colorReturn = distinctColors[i];
      biggestDifference = sqrt(pow(r - distinctRGB[i][0],2) + pow(g - distinctRGB[i][1],2) + pow(b - distinctRGB[i][2],2));
    }
  }
  return colorReturn;
}

此函数使用Math.h 以减少输入次数。

【讨论】:

  • 非常有帮助!你能解释一下你是怎么来int biggestDifference = 1000;的吗?我不明白 1000 的价值从何而来以及为什么。谢谢!
  • @Systembolaget 1000 大于 255*3,所以我只是选择了一些大于 765 的数字作为初始值
  • 好的,谢谢;我想知道那个似乎不知从何而来的“神奇数字”。我使用的颜色传感器输出 ~9000 作为 r、g 和 b 的最大值,所以我应该使用 9000*3。
猜你喜欢
  • 2014-09-01
  • 2019-08-17
  • 1970-01-01
  • 2011-05-09
  • 2019-07-02
  • 1970-01-01
  • 2011-05-27
相关资源
最近更新 更多