samzmann
samzmann

Reputation: 2566

Get pixel brightness with p5.js

I'm trying to get the pixel data from an image to calculate the image's average brightness. I have no problem accessing the data with img.loadPixels(); but for some reason some elements of the pixel array are undefined, which breaks my computation.

Here is the code for sketch.js:

var img;
var brightness;
var inc;
var gotBright = false;

function preload(){
   img = loadImage('assets/2.png');
}

function setup(){
   createCanvas(500, 500);
   background(0);

}

function draw(){

   img.resize(10, 10);
   image(img, 0, 0, img.width, img.height);

   brightness = 0;
   inc = 0;

   if (gotBright == false) {

      img.loadPixels();
      loadPixels();
      for (var i = 0; i < img.width; i++) {
         for (var j = 0; j < img.height; j++) {
            var index = (i * j * img.width) * 4;
            var r = img.pixels[index + 0];
            var g = img.pixels[index + 1];
            var b = img.pixels[index + 2];

            brightness += (r + g + b) / 3;
            inc ++;
            console.log(inc, r , g, b);
         }
      }
      gotBright = true;
      brightness = brightness/inc;
   }
}

brightness should be equal to some number between 0 and 255, but now it's NaN...

If you have recommendations on other methods to calculate average brightness of an image, I am happy to hear them :) Thanks!

Upvotes: 0

Views: 2256

Answers (2)

Kevin Workman
Kevin Workman

Reputation: 42176

Bauer's answer is on the right track. You need to make sure your pixel index is correct. The best way to do that is to get out a piece of graph paper and draw out some examples.

Or you could just use the get() function that takes an x and a y parameter. From the reference:

var myImage;
var c;

function preload() {
  myImage = loadImage("assets/rockies.jpg");
}

function setup() {
  background(myImage);
  noStroke();
  c = myImage.get(60, 90);
  fill(c);
  rect(25, 25, 50, 50);
}

Upvotes: 0

Bauer Marius
Bauer Marius

Reputation: 180

I think your index calculation is wrong. Shouldn't it be:

var index = (i + j * img.width) * 4;

Upvotes: 3

Related Questions