Nadesłany przez Tomasz Lubiński, 25 listopada 2011 00:03
Kod przedstawiony poniżej przedstawia główną część rozwiązania problemu.Pobierz pełne rozwiązanie.
Jeżeli nie odpowiada Ci sposób formatowania kodu przez autora skorzystaj z pretty printer'a i dostosuj go automatycznie do siebie.
sierra2.js:
//Algorytm Sierra 2 //(c) 2011 by Tomasz Lubinski //www.algorytm.org /* Data of the image */ var imageData; /* shift used by errors array (to avoid indexes less than 0) */ var shift = 2; /* Sierra 2 algorithm */ function sierra2() { var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); // read the width and height of the canvas var width = canvas.width; var height = canvas.height; // initialize array with errors errors = new Array(height+1); for (var i=0; i<height+1; i++) { errors[i] = new Array(width+4); for (var j=0; j<width+4; j++) { errors[i][j] = 0; } } // perform Sierra 2 algorithm for (var i=0; i<height; i++) { for (var j=0; j<width; j++) { index = (i*width+j)*4; val = 0.299*imageData.data[index+0] + 0.587*imageData.data[index+1] + 0.114*imageData.data[index+2]; val += errors[i][j+shift]; if (val > 126) { // set pixel white imageData.data[index+0] = 255; imageData.data[index+1] = 255; imageData.data[index+2] = 255; error = val - 255; } else { // set pixel black imageData.data[index+0] = 0; imageData.data[index+1] = 0; imageData.data[index+2] = 0; error = val; } // distribute error introduced by set pixel white/black operation errors[i ][j+1+shift] += (error*4.0/16.0); errors[i ][j+2+shift] += (error*3.0/16.0); errors[i+1][j-2+shift] += (error*1.0/16.0); errors[i+1][j-1+shift] += (error*2.0/16.0); errors[i+1][j +shift] += (error*3.0/16.0); errors[i+1][j+1+shift] += (error*2.0/16.0); errors[i+1][j+2+shift] += (error*1.0/16.0); } } // copy the image data back onto the canvas ctx.putImageData(imageData, 0, 0); } /* load image pointed by param_file to canvas */ function loadImage(imgSrc) { var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); // add file:// if user specified local path if (imgSrc.indexOf("//") == -1 && imgSrc.indexOf(".") != 0) { imgSrc = "file:///" + imgSrc; } // load file into canvas var img = new Image(); img.onload = function(){ var width = img.width; var height = img.height; canvas.width = width; canvas.height = height; ctx.drawImage(img,0,0); // replace transparent with white try { imageData = ctx.getImageData(0, 0, width, height); } catch(e) { netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead"); imageData = ctx.getImageData(0, 0, width, height); } for (var i=0; i<height; i++) { for (var j=0; j<width; j++) { index = (i*width+j)*4; if (imageData.data[index+3] == 0) { imageData.data[index+3] = 255; imageData.data[index+0] = 255; imageData.data[index+1] = 255; imageData.data[index+2] = 255; } } } } img.src = imgSrc; }