# Color to grayscale algorithm

**URL:** <https://discourse.processing.org/t/color-to-grayscale-algorithm/45171>\
**Category:** Processing.py\
**Created:** [October 12, 2024, 8:30am UTC](https://discourse.processing.org/t/color-to-grayscale-algorithm/45171 "2024-10-12T08:30:24Z")\
**Posts on this page:** 1\
**Showing post:** 5

<div class="post-metadata">

**Author:** ![solub](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/solub/32/333_2.png) [@solub](https://discourse.processing.org/u/solub)\
**Post date:** [October 12, 2024, 4:50pm UTC](https://discourse.processing.org/t/color-to-grayscale-algorithm/45171/5 "2024-10-12T16:50:32Z")

</div>

The technical term you’re looking for is [Relative Luminance](https://en.wikipedia.org/wiki/Relative_luminance). It is a specific standard for calculating the brightness of colors as perceived by humans, with scientifically derived weights.

A rather well-illustrated Twitter/X [thread](https://x.com/timsoret/status/1251763478177644544) on the subject.

Although the Processing algorithm for grayscale conversion (using `filter(GRAY)`) is not an exact implementation of _relative luminance_, it’s conceptually similar and a close approximation for general use (only the weights differ slightly).

For comparison, here’s what the grayscale conversion function would look like if it used perceptual precision weightings.

```auto
def relative_luminance(img):
    
    """
    Convert the image to grayscale using true relative luminance weights and bit shifting.
    Reference -> https://en.wikipedia.org/wiki/Relative_luminance
    
    """
    
    lum_img = createImage(img.width, img.height, RGB)
    
    img.loadPixels()
    lum_img.loadPixels()
    
    for i in range(len(img.pixels)):
        
        col = img.pixels[i]
        
        # Extract RGB components using bit shifts
        r = (col >> 16) & 0xff # Red component
        g = (col >> 8) & 0xff # Green component
        b = col & 0xff # Blue component
        
        # Calculate the true relative luminance using scaled weights:
        # Luminance = 0.2126 * Red + 0.7152 * Green + 0.0722 * Blue
        # Approximation: 0.2126 * 256 = 54, 0.7152 * 256 = 183, 0.0722 * 256 = 18
        lum = (54 * r + 183 * g + 18 * b) >> 8 # Bit-shift by 8 (dividing by 256)
        
        # Set the grayscale pixel by combining the luminance value into RGB format
        lum_img.pixels[i] = (col & 0xff000000) | (lum << 16) | (lum << 8) | lum
    
    lum_img.updatePixels()
    
    return lum_img

```

![grayscale](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/3X/9/5/9510ef3a4e3638957fc0d55bb78b01a8603310fb.webp)

---

_[View the full topic](https://discourse.processing.org/t/color-to-grayscale-algorithm/45171)._
