It's easy to blend()
two images using p5.js, which is great, but I would like to be able to equalize the histogram of the resulting blended image. Something like -equalize
in ImageMagick. Does anyone know how to do this in p5.js?
Asked
Active
Viewed 833 times
1 Answers
1
You can do this, sure. Algo: For each channel calculate cumulative normalized histograms multiplied by maximum value in that channel - this will be your new pixel values in channel given old value.
I've read algo description in GeeksforGeeks portal and ported it to p5.js, code:
let img
let mod
// helpers
function getMappings() {
hists = [[], [], []];
newlevels = [[], [], []];
maxval = [-1, -1, -1];
// RGB histograms & maximum pixel values
for (let i = 0; i < img.width; i++) {
for (let j = 0; j < img.height; j++) {
let c = img.get(i, j);
hists[0][c[0]] = (hists[0][c[0]] || 0) + 1;
hists[1][c[1]] = (hists[1][c[1]] || 0) + 1;
hists[2][c[2]] = (hists[2][c[2]] || 0) + 1;
for (let ch=0; ch < 3; ch++) {
if (c[ch] > maxval[ch]) {
maxval[ch] = c[ch];
}
}
}
}
// New intensity levels based on cumulative, normalized histograms
for (let hi = 0; hi < 3; hi++) {
let acc = 0;
for (let lev=0; lev < 256; lev++) {
acc += hists[hi][lev];
newlevels[hi][lev] = Math.round(maxval[hi]*acc/(img.width*img.height));
}
}
return newlevels;
}
function equalizeHistograms() {
let map = getMappings();
for (let i = 0; i < mod.width; i++) {
for (let j = 0; j < mod.height; j++) {
let c = img.get(i, j);
let newcol = color(map[0][c[0]], map[1][c[1]], map[2][c[2]]);
mod.set(i, j, newcol);
}
}
mod.updatePixels();
}
// system functions
function preload() {
img = loadImage('https://i.imgur.com/00HxCYr.jpg');
mod = createImage(200, 140);
}
function setup() {
img.loadPixels();
mod.loadPixels();
createCanvas(250, 400);
equalizeHistograms();
}
function draw() {
image(img,0,0);
image(mod,0,140);
}

Agnius Vasiliauskas
- 10,935
- 5
- 50
- 70
-
Thanks Agnius, this looks great, will try out now. – B-30 Sep 28 '19 at 08:24
-
1Works great! Thanks Agnius. Thanks also for a great demo on how to get a generic algorithm and specify it in a given language, in this case p5.js – B-30 Sep 28 '19 at 09:00
-
you are wellcome – Agnius Vasiliauskas Sep 28 '19 at 13:07