Assafi Cohen-Arazi
Assafi Cohen-Arazi

Reputation: 847

Finding which color is the closest to the given RGB values in C

Here is a website that contains 20 colors that are the most simple and distinct: http://sashat.me/2017/01/11/list-of-20-simple-distinct-colors/

I am making a program that detects colors and gives them a name.

The problem is that I need a function that would:

Here are some examples of the ideal function:

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

Any help on how to make something like this would be appreciated! Thanks!

Upvotes: 2

Views: 2211

Answers (1)

Assafi Cohen-Arazi
Assafi Cohen-Arazi

Reputation: 847

I've answered my own question in order to help future viewers.

Using the color difference formula found on the wikipedia and shown in the comments, this function will take in 3 parameters and return the closest color.

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;
}

This function uses Math.h in order to do the formula with less typing.

Upvotes: 3

Related Questions