Color to grayscale algorithm

Processing Java version:

/*
 Project:   Grayscale
 Author:    GLV
 Date:      2024-10-12
 Version:   1.0.0
*/

// References:
// https://github.com/benfry/processing4/blob/main/core/src/processing/core/PImage.java#L874
// https://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale

String url = "http://learningprocessing.com/code/assets/sunflower.jpg";
PImage img, img0; 
int h, w;

void settings()
  {
  img0 = loadImage(url);
  img0.resize(400, 400);
  w = img0.width;
  h = img0.height;
  println(w, h);
  size(w, h);
  }

//void setup()
//  {
//  }

void draw()
  {
  img = img0.copy();   
  img.loadPixels();
  int lum = 0;
  int mx = mouseX;
  
  for(int y=0; y<img.width; y++)
  //for(int y=mouseY; y<img.width; y++) // If you want to see color!
    {
    for(int x=0; x<img.width; x++)
      {
      int loc = x+y*img.width;  
      
      // Beginner friendly.
      // Below is much faster with bit shifting!
      float r = red(img.pixels[loc]);
      float g  = green(img.pixels[loc]);
      float b  = blue(img.pixels[loc]);
       
      if (x < mx)
        lum = (int) (77*r + 151*g + 28*b)/256;  // 0.299  0.587  0.114   weights
      else
        lum = (int) (54*r + 183*g + 18*b)/256;   // 0.2126 0.7152 0.0722  weights
        //lum = (int) (r + g + b)/3;            // Averaging 
      img.pixels[loc] = color(lum); 
      } 
    }
  img.updatePixels(); 
  
  image(img, 0, 0);
  stroke(255);
  line(mouseX, 0, mouseX, height);
  }

image

:)

1 Like