xxxxxxxxxx
119
// histogram equalization
let cam;
let hist = Array(256).fill(0);
let nmap = Array(256).fill(0);
let norm = 600;
function rgb2gray(img) {
let nimg = img.get(); // alternatively createImage(img.width, img.height)
nimg.loadPixels();
for (let i = 0; i < nimg.pixels.length; i += 4) {
const Y =
0.3 * nimg.pixels[i] +
0.59 * nimg.pixels[i + 1] +
0.11 * nimg.pixels[i + 2];
nimg.pixels[i] = nimg.pixels[i + 1] = nimg.pixels[i + 2] = Y;
}
nimg.updatePixels();
return nimg;
}
function setup() {
createCanvas(640, 480);
cam = createCapture(VIDEO);
cam.size(width / 2, height / 2);
cam.hide();
textSize(18);
}
function drawhist(h, x) {
let sum = 0;
noStroke();
for (let i = 0; i < h.length; i++) {
fill(i);
sum += h[i];
rect(i + (width / 2) * x, height / 2, 1, h[i] / (norm / 60));
rect(i + (width / 2) * x, height - sum / norm, 1, sum / norm);
fill(255, 0, 0);
rect(i + (width / 2) * x, height - sum / norm, 2, 2);
fill(0, 255, 0);
rect(i + (width / 2) * x, height / 2 + h[i] / 10, 2, 2);
}
}
function calchist(img, h) {
img.loadPixels();
for (let i = 0; i < h.length; i++) {
h[i] = 0;
}
for (let i = 0; i < img.pixels.length; i += 4) {
let g = img.pixels[i];
h[g]++;
}
}
function draw() {
let frame = rgb2gray(cam);
background(0, 0, 48);
image(frame, 0, 0);
frame.loadPixels();
calchist(frame, hist);
drawhist(hist, 0);
let min_u = -1;
for (let i = 0; i < hist.length; i++) {
if (hist[i] != 0) {
min_u = i;
break;
}
}
let max_u = -1;
for (let i = hist.length - 1; i >= 0; i++) {
if (hist[i] != 0) {
max_u = i;
break;
}
}
let a = -min_u;
let b = 255 / (max_u - min_u);
let cdf = 0;
for (let i = 0; i < hist.length; i++) {
cdf += hist[i];
nmap[i] = int((255 * cdf) / (frame.pixels.length / 4));
//nmap[i] = b * (i + a);
}
for (let i = 0; i < frame.pixels.length; i += 4) {
let ivalue = frame.pixels[i];
frame.pixels[i] = nmap[ivalue];
frame.pixels[i + 1] = nmap[ivalue];
frame.pixels[i + 2] = nmap[ivalue];
}
frame.updatePixels();
calchist(frame, hist);
drawhist(hist, 1);
image(frame, width / 2, 0);
stroke(255);
line(width / 2, 0, width / 2, height);
line(0, height / 2, width, height / 2);
fill(255, 0, 0);
noStroke();
text("CDF", width - 45, height - 50);
text("CDF", width / 2 - 45, height - 50);
fill(0, 255, 0);
text("PDF", width - 45, height / 2 + 50);
text("PDF", width / 2 - 45, height / 2 + 50);
}