Home > database >  rgb to greyscale converter
rgb to greyscale converter

Time:06-12

Is there a function that converts rgb colours directly into their true greyscale form?

function rgbToGrayscale(red, green, blue) {
    const gray = []

    /* ---- CONVERSION CODE ---- */

    return gray
}

// color
const rgb = [20, 150, 240]

// grayscale conversion
const gray = rgbToGrayscale(rgb[0], rgb[1], rgb[2]) // [121, 121, 121]

I would greatly appreciate it if anyone can find a simple answer to this problem.

CodePudding user response:

Thanks to @Spektre and @Teemu , the function now works. I found this article inside @Spektre 's stackoverflow link useful as well.


If you want a cheap greyscale colour conversion, just add the numbers together and divide it by three:

function rgbToGrayscale(red, green, blue) {
    const gray = (red   green   blue) / 3

    return [gray, gray, gray]
}

const gray = rgbToGrayscale(20, 150, 240) // [136.6, 136.6, 136.6]

But because our eyes mix up light and colour, people have found that, to us, blue is dimmer than red, and red is dimmer than green. Thus, multiple formulas have been created and refined that balance the colours for the human eye.

This is one that I found quite good:

function rgbToGrayscale(red, green, blue) {
    /* remember: if you multiply a number by a decimal between 0
    and 1, it will make the number smaller. That's why we don't
    need to divide the result by three - unlike the previous
    example - because it's already balanced. */

    const r = red * .3 // ------> Red is low
    const g = green * .59 // ---> Green is high
    const b = blue * .11 // ----> Blue is very low

    const gray = r   g   b

    return [gray, gray, gray]
}

const rgb = [20, 150, 240]
const gray = rgbToGrayscale(rgb[0], rgb[1], rgb[2])

console.log(rgb)
console.log(gray)

  • Related