Last active
June 8, 2020 19:06
-
-
Save KrabCode/522afeb9b11435f25cff1978027c4500 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| int glyphRowsAndColumns = 19; | |
| int resultGlyphSize = 10; | |
| int glyphSize; | |
| ArrayList<Glyph> glyphs = new ArrayList<Glyph>(); | |
| PImage sourceImage; | |
| PGraphics pg; | |
| boolean displayResult = true; | |
| void setup() { | |
| size(800, 800, P2D); | |
| PImage grid = loadImage("grid.png"); | |
| glyphSize = (grid.width / glyphRowsAndColumns); | |
| loadGlyphs(grid); | |
| loadAndComposeImage(); | |
| } | |
| void loadAndComposeImage() { | |
| sourceImage = loadImage("https://picsum.photos/800.jpg"); | |
| composeImageFromGlyphs(sourceImage); | |
| } | |
| void draw() { | |
| background(255); | |
| image(displayResult?pg:sourceImage, 0, 0, width, height); | |
| } | |
| void keyPressed() { | |
| loadAndComposeImage(); | |
| } | |
| void mousePressed() { | |
| displayResult = !displayResult; | |
| } | |
| void loadGlyphs(PImage grid) { | |
| for (int x = 0; x < grid.width; x += glyphSize) { | |
| for (int y = 0; y < grid.height; y += glyphSize) { | |
| Glyph a = new Glyph(); | |
| a.img = grid.get(x, y, glyphSize, glyphSize); | |
| a.brightness = getAverageBrightness(a.img); | |
| glyphs.add(a); | |
| } | |
| } | |
| } | |
| float getAverageBrightness(PImage source) { | |
| float sum = 0; | |
| int count = 0; | |
| for (int x = 0; x < source.width; x++) { | |
| for (int y = 0; y < source.height; y++) { | |
| count++; | |
| sum += brightness(source.get(x, y)); | |
| } | |
| } | |
| return sum / count; | |
| } | |
| void composeImageFromGlyphs(PImage source) { | |
| pg = createGraphics(width, height, P2D); | |
| pg.beginDraw(); | |
| for (int x = 0; x < width; x+=resultGlyphSize) { | |
| for (int y = 0; y < height; y+=resultGlyphSize) { | |
| float sourceBrightness = getAverageBrightness(source.get(x, y, resultGlyphSize, resultGlyphSize)); | |
| Glyph matchingGlyph = findGlyphWithClosestBrightness(sourceBrightness); | |
| pg.image(matchingGlyph.img, x, y, resultGlyphSize, resultGlyphSize); | |
| } | |
| } | |
| pg.endDraw(); | |
| } | |
| Glyph findGlyphWithClosestBrightness(float brightness) { | |
| Glyph result = glyphs.get(0); | |
| float closestDistanceToBrightness = 1000; | |
| for (Glyph g : glyphs) { | |
| float distanceToThisBrightness = abs(brightness - g.brightness); | |
| if (distanceToThisBrightness < closestDistanceToBrightness) { | |
| closestDistanceToBrightness = distanceToThisBrightness; | |
| result = g; | |
| } | |
| } | |
| return result; | |
| } | |
| class Glyph { | |
| PImage img; | |
| float brightness; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment