Created
May 9, 2022 09:11
-
-
Save companje/86645c4183c9073ceb7639f1c37b7905 to your computer and use it in GitHub Desktop.
Dither
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Coding Challenge #90: Floyd-Steinberg Dithering | |
//https://www.youtube.com/watch?v=0L2n8Tg2FwI | |
PImage img; | |
void setup() { | |
size(1024, 512); | |
img = loadImage("duck.png"); | |
img.filter(GRAY); | |
background(0); | |
image(img, 0, 0); | |
applyDithering(img,1); | |
image(img, 512, 0); | |
} | |
void draw() { | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Coding Challenge #90: Floyd-Steinberg Dithering | |
//https://www.youtube.com/watch?v=0L2n8Tg2FwI | |
int index(PImage img, int x, int y) { | |
return y*img.width+x; | |
} | |
PImage applyDithering(PImage img, int factor) {//factor is num colors per channel (1=black/white) | |
img.loadPixels(); | |
for (int y = 0; y<img.height-1; y++) { | |
for (int x = 1; x<img.width-1; x++) { | |
color pix = img.pixels[index(img,x, y)]; | |
float oldR = red(pix); | |
float oldG = green(pix); | |
float oldB = blue(pix); | |
int newR = round(factor * oldR / 255) * (255/factor); | |
int newG = round(factor * oldG / 255) * (255/factor); | |
int newB = round(factor * oldB / 255) * (255/factor); | |
img.pixels[index(img, x, y)] = color(newR, newG, newB); | |
float errR = oldR-newR; | |
float errG = oldG-newG; | |
float errB = oldB-newB; | |
ditherPass(img, x+1, y, errR, errG, errB, 7/16.); | |
ditherPass(img, x, y+1, errR, errG, errB, 5/16.); //volgorde belangrijk? | |
ditherPass(img, x-1, y+1, errR, errG, errB, 3/16.); | |
ditherPass(img, x+1, y+1, errR, errG, errB, 1/16.); | |
} | |
} | |
img.updatePixels(); | |
return img; | |
} | |
void ditherPass(PImage img, int x, int y, float errR, float errG, float errB, float w) { | |
int index = index(img, x, y); | |
color c = img.pixels[index]; | |
float r = red(c); | |
float g = green(c); | |
float b = blue(c); | |
r += errR * w; | |
g += errG * w; | |
b += errB * w; | |
img.pixels[index] = color(r, g, b); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment