xxxxxxxxxx
101
function preload(){
orig = loadImage('tsunami.jpg');
}
function setup() {
orig.resize(400, 0)
createCanvas(orig.width, orig.height*2);
background(50);
frameRate(0);
draw();
}
function draw() {
image(orig, 0, 0);
dithered = ditherImage(orig);
image(dithered, 0, orig.height);
}
//from https://en.wikipedia.org/wiki/Floyd%E2%80%93Steinberg_dithering
function ditherImage(img){
let oldPixel, newPixel;
let dithered = createImage(img.width, img.height);
console.log(getColor(img, 0, 0))
img.loadPixels();
dithered.loadPixels();
for(y = 0; y < img.height; y++){
for(x = 0; x < img.width; x++){
oldPixel = getColor(img, x, y);
newPixel = findColor(oldPixel);
writeColor(dithered, x, y, newPixel[0], newPixel[1], newPixel[2], newPixel[3]);
quant_error = quantError(oldPixel, newPixel);
let c1 = addColor(getColor(dithered, x+1, y ), multColor(quant_error, (7/16)));
let c2 = addColor(getColor(dithered, x-1, y+1), multColor(quant_error, (3/16)));
let c3 = addColor(getColor(dithered, x , y+1), multColor(quant_error, (5/16)));
let c4 = addColor(getColor(dithered, x+1, y+1), multColor(quant_error, (1/16)));
writeColor(dithered, x+1, y , c1[0], c1[1], c1[2], c1[3]);
writeColor(dithered, x-1, y+1, c2[0], c2[1], c2[2], c2[3]);
writeColor(dithered, x , y+1, c3[0], c3[1], c3[2], c3[3]);
writeColor(dithered, x+1, y+1, c4[0], c4[1], c4[2], c4[3]);
}
}
dithered.updatePixels();
return dithered;
}
function multColor(c, mult){
return([
c[0] * mult,
c[1] * mult,
c[2] * mult,
c[3] * mult,
])
}
function addColor(c1, c2){
return([
c1[0] + c2[0],
c1[1] + c2[1],
c1[2] + c2[2],
c1[3] + c2[3],
])
}
function findColor(c){
closest = [
round(c[0]/255),
round(c[1]/255),
round(c[2]/255),
round(c[3]/255)
];
return(closest);
}
function quantError(o, n){
return([
o[0] - n[0],
o[1] - n[1],
o[2] - n[2],
o[3] - n[3],
])
}
function getColor(image, x, y){
let index = (x + y * image.width) * 4;
image.loadPixels();
return([
image.pixels[index ],
image.pixels[index + 1],
image.pixels[index + 2],
image.pixels[index + 3],
]);
}
function writeColor(image, x, y, red, green, blue, alpha) {
let index = (x + y * width) * 4;
image.pixels[index] = red;
image.pixels[index + 1] = green;
image.pixels[index + 2] = blue;
image.pixels[index + 3] = alpha;
}