查找哪种颜色最接近 C 中给定的 RGB 值
Finding which color is the closest to the given RGB values in C
这是一个包含 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
任何关于如何制作这样的东西的帮助将不胜感激!谢谢!
为了帮助未来的观众,我已经回答了我自己的问题。
使用在维基百科上找到并在评论中显示的色差公式,此函数将接受 3 个参数和 return 最接近的颜色。
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
以减少键入的公式。
这是一个包含 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
任何关于如何制作这样的东西的帮助将不胜感激!谢谢!
为了帮助未来的观众,我已经回答了我自己的问题。
使用在维基百科上找到并在评论中显示的色差公式,此函数将接受 3 个参数和 return 最接近的颜色。
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
以减少键入的公式。