简体   繁体   中英

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!

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM