Problem Statement and Background Image and Video filters Ascii art Photo Mosaic
Ascii art is the technique that uses characters of the ASCII alphabet to create images based on the level of illumination of each pixel. To create this kind of images is necessary to extract the illuminance of the pixels; that's why the process starts by transforming the initial image applying a grayscale filter, then depending on the level of the illuminance of each pixel, a character is selected. The selection of the characters is based on its density, i.e., if we have a dark zone is better to choose characters like @ than - because the first one fills a bigger space than the second character. Additionally it is preferable to use monospace fonts (fonts whose letters and characters each occupy the same amount of horizontal space), because it allows us to perfectly align the characters.
The markdown of the above sketch looks like:
1link> :P5 sketch=/docs/sketches/ascii_art.js, width=500, height=500
And the p5 sketch that creates the ascii art is the following:
1linklet img;
2linklet div;
3linkvar options = [' ','`','.','-',":",';','"','*','!',
4link'=','>','L','i','/','?','J','r','x','7','z',
5link'3','C','n','F','P','w','S','E',
6link'N','9','T','$','Q','M','%','@','b',
7link'D','&','R','B'];
8linkfunction preload() {
9link img = loadImage('/vc/docs/sketches/lenna.png');
10link}
11link
12linkfunction setup() {
13link createCanvas(500, 500);
14link div = createP('');
15link div.style('font-family', 'monospace');
16link
17link img.loadPixels();
18link let d = pixelDensity();
19link let fullImage = (img.width * d) * (img.height * d);
20link for (let i = 0; i < fullImage; i++) {
21link let r = img.pixels[i*4];
22link let g = img.pixels[i*4+1];
23link let b = img.pixels[i*4+2];
24link
25link let gray = r *0.2126 + g *0.7152 + b *0.0722;
26link
27link img.pixels[i*4] = gray;
28link img.pixels[i*4+1] = gray;
29link img.pixels[i*4+2] = gray;
30link }
31link img.updatePixels();
32link var res = '<pre>';
33link for (var i=0; i<img.height; i++) {
34link var line = '';
35link for (var j=0; j<img.width; j++) {
36link let index = (j + i*img.width)*4;
37link
38link var x = img.pixels[index];
39link
40link var v = round((1-x/255.0)*40);
41link
42link var chr = options[v];
43link if (chr==' ') chr=' ';
44link if (chr=='<') chr='<';
45link if (chr=='>') chr='>';
46link if (chr=='"') chr='"';
47link line += chr;
48link }
49link res += line+'<br>';
50link }
51link res += '</pre>'
52link div.html(res);
53link div.style('font-size', '1px');
54link div.style('letter-spacing', '0.4em');
55link div.style('line-height', '1em')
56link div.position(0, 0);
57link
58link}
59link
Problem Statement and Background Image and Video filters Ascii art Photo Mosaic