extract(font, function (err, data) { if (err) throw err var code = String((process.argv[2] || 'a').charCodeAt(0)) var glyph = data.glyphs[code] var rgba = toRGBA(glyph) save(rgba, 'png').pipe(process.stdout) })
co(function*(){ yield processImages(pattern, listOfImages, blockLength, db); var pixels = ndarray([], [640, 640, 3]); for(var i=0; i<pattern.length; i+=blockLength){ var block = yield pickBlock("B-"+i); for(var k=0; k<blockLength; k++){ var pixel = block[k]; if(pixel!==null){ var channels = pixel.split("-").map(function(v){ return parseInt(v, 16); }); pixels.set(pattern[i+k][0], pattern[i+k][1], 0, channels[0]); pixels.set(pattern[i+k][0], pattern[i+k][1], 1, channels[1]); pixels.set(pattern[i+k][0], pattern[i+k][1], 2, channels[2]); } } } savePixels(pixels, "jpg").pipe(fs.createWriteStream("./test.jpg")); }).then(sketchSaver).catch(function(err){
getPixels(input.src, function(err, pixels) { if (err) { console.log("Bad Image path"); return; } var width = 0; for (var i = 0; i < pixels.shape[0]; i++) width++; for (var i = 0; i < pixels.shape[0]; i++) { for (var j = 0; j < pixels.shape[1]; j++) { let val = (i / width) * 255; pixels.set(i, j, 0, val); pixels.set(i, j, 1, val); pixels.set(i, j, 2, val); pixels.set(i, j, 3, 255); } } var chunks = []; var totalLength = 0; var r = savePixels(pixels, input.format, { quality: 100 }); r.on("data", function(chunk) { totalLength += chunk.length; chunks.push(chunk); }); r.on("end", function() { var data = Buffer.concat(chunks, totalLength).toString("base64"); var datauri = "data:image/" + input.format + ";base64," + data; output(input.image, datauri, input.format); callback(); }); });
co(function*(){ var START = 640; var END = 3600; var GROWTH = END/START; var SAMPLE_SIZE = 2; var baseImg = yield getBasePixels(sourcefile); var endImg = ndarray([], [END, END, 3]); var onePercent = END/100; var fivePercent = onePercent*5; var lastAlert = 0; var nextGoal = 5; console.time(nextGoal+"% "+destfile); for(var x=0; x<END; x++){ var rowId = "row"; var distTime = 0; for(y=0; y<END; y++){ var mx = Math.floor(x / GROWTH); var my = Math.floor(y / GROWTH); var sx = Math.max(mx - SAMPLE_SIZE, 0); var ex = mx + SAMPLE_SIZE; var sy = Math.max(my - SAMPLE_SIZE, 0); var ey = my + SAMPLE_SIZE; var red = 0; var green = 0; var blue = 0; var count = 0; for(var cx=sx; cx<ex; cx++){ for(var cy=sy; cy<ey; cy++){ red += baseImg.get(cx,cy,0); green += baseImg.get(cx,cy,1); blue += baseImg.get(cx,cy,2); count++; } } endImg.set(x, y, 0, Math.floor(red / count)); endImg.set(x, y, 1, Math.floor(green / count)); endImg.set(x, y, 2, Math.floor(blue / count)); } if(x > lastAlert + fivePercent){ lastAlert = x; console.timeEnd(nextGoal+"% "+destfile); nextGoal = nextGoal + 5; console.time(nextGoal+"% "+destfile); } } savePixels(endImg, "jpg").pipe(fs.createWriteStream(destfile)); }).catch(function(err){
pyramid.forEach(function(level, i) { var img = new Image(); img.src = savePixels(level, 'canvas').toDataURL(); img.style.border = '1px dotted black'; document.body.appendChild(document.createElement('br')); document.body.appendChild(img); document.body.appendChild(document.createTextNode(' level #'+i+' ('+img.width+'x'+img.height+')')); });
co(function*(){ //yield processImages(pattern, listOfImages, blockLength, db); var pixels = yield crushIt(1, 2); savePixels(pixels, "jpg").pipe(fs.createWriteStream("./test.jpg")); }).then(sketchSaver).catch(function(err){
getPixels(imgPath, function(err, pixels) { if (err) { throw err; } function getRGB(x, y) { return (pixels.get(x, y, 0) + pixels.get(x, y, 1) + pixels.get(x, y, 2)) / 3 | 0; } function dropY(x, maxY) { var y = 0; var points = []; for (; y < maxY; y++) { if (intBlack(getRGB(x, y))) { points.push([x, y]); return points; } } return points; } function dropX(y, maxX) { var x = 0; var points = []; for (; x < maxX; x++) { if (intBlack(getRGB(x, y))) { points.push([x, y]); } } return points; } var width = pixels.shape[0]; var height = pixels.shape[1]; var black = []; for (var x = 0; x < width; x++) { joinPoints(black, dropY(x, height)); } var topEdge = findTopEdge(removeOutliers(black, 80)); black.forEach(function(xy) { var x = xy[0]; var y = xy[1]; setColour(pixels, x, y, {green: 255}); }); topEdge.points.forEach(function(xy) { var x = xy[0]; var y = xy[1]; setColour(pixels, x, y, {red: 255}); }); // var outImage = zeros([width, height, 4]); // imageRotate(outImage, pixels, -Math.atan(topEdge.equation[0]), 0, 0); savePixels(pixels, 'jpeg').pipe(tmp); });
co(function*(){ var IMG_SIZE = 640; var numImgs = listOfImages.length; var imgLength = IMG_SIZE * IMG_SIZE; var fivePercent = imgLength/20; var pixels = ndarray([], [IMG_SIZE, IMG_SIZE, 3]); var imgs = []; for(var b=0; b<numImgs; b++){ var imgId = listOfImages[b]; var imgPath = path.join(__dirname, "../../instagrams", imgId+".jpg"); console.log("parse "+imgPath+" "+b+" of "+numImgs); console.time("report"); var img = yield getBasePixels(imgPath); imgs.push(img); } var fork = pattern(IMG_SIZE); var avgs = []; for(var i=0; i<imgLength; i++){ var pos = fork.next().value; var x = pos[0]; var y = pos[1]; avgs.push(getAvg(imgs, x, y)); } for(var i=0; i<imgLength; i++){ var left = i - 3 < 0 ? 0 : i - 3; var right = i + 3 >= imgLength ? imgLength-1 : i + 3; var leftAvg = avgs[left]; var rightAvg = avgs[right]; var redDif = leftAvg.red - rightAvg.red; var greenDif = leftAvg.green - rightAvg.green; var blueDif = leftAvg.blue - rightAvg.blue; var midAvg = { red: leftAvg.red + redDif, green: leftAvg.green + greenDif, blue: leftAvg.blue + blueDif, } var close = findClose(imgs, midAvg, avgs[i]); pixels.set(avgs[i].x, avgs[i].y, 0, close.red); pixels.set(avgs[i].x, avgs[i].y, 1, close.green); pixels.set(avgs[i].x, avgs[i].y, 2, close.blue); } savePixels(pixels, "jpg").pipe(fs.createWriteStream("./test.jpg")); }).then(sketchSaver).catch(function(err){
/** * Write the output to an image * @param output */ write(output){ //convert to ndarray for saving var ndShifted = Utils.pixVal_to_nd(this.pixVals); //save image var writeStream = fs.createWriteStream(output); var extension = output.match(/\.[0-9a-z]+$/)[0]; savePixels(ndShifted, extension).pipe(writeStream); }
getPixels(imgPath, function(err, pixels) { if (err) { throw err; } function getRGB(x, y) { return (pixels.get(x, y, 0) + pixels.get(x, y, 1) + pixels.get(x, y, 2)) / 3 | 0; } function dropY(x, maxY) { var y = 0; for (; y < maxY; y++) { if (intBlack(getRGB(x, y))) { return y; } } return -1; } function dropX(y, maxX) { var x = 0; for (; x < maxX; x++) { if (intBlack(getRGB(x, y))) { return x; } } return -1; } var width = pixels.shape[0]; var height = pixels.shape[1]; var top = []; for (var x = 0; x < width; x++) { let y = dropY(x, height); if (y !== -1) { pixels.set(x, y, 0, 255); pixels.set(x, y, 1, 0); pixels.set(x, y, 2, 0); pixels.set(x, y, 3, 0); } } for (var y = 0; y < height; y++) { let x = dropX(y, width); if (x !== -1) { pixels.set(x, y, 0, 255); pixels.set(x, y, 1, 0); pixels.set(x, y, 2, 0); pixels.set(x, y, 3, 0); } } savePixels(pixels, 'jpeg').pipe(tmp); });
return function getExporterFn (options, cb) { // If we have a custom background, fill it in (otherwise default is transparent black `rgba(0, 0, 0, 0)`) var ndarray = this.ndarray; if (options.background) { ndarrayFill(ndarray, function fillBackground (i, j, k) { return options.background[k]; }); } // Add each image to the canvas var images = this.images; images.forEach(function getUrlPath (imageObj) { // Iterate over the image's data across its rows // setting the original data at that offset // [1, 2, 0, 0, // 3, 4, 0, 0, // 0, 0, 5, 0, // 0, 0, 0, 6] var img = imageObj.img; var xOffset = imageObj.x; var yOffset = imageObj.y; var colIndex = 0; var colCount = img.width; // DEV: Use `width` for padding for (; colIndex < colCount; colIndex += 1) { var rowIndex = 0; var rowCount = img.height; // DEV: Use `height` for padding for (; rowIndex < rowCount; rowIndex += 1) { var rgbaIndex = 0; var rgbaCount = 4; for (; rgbaIndex < rgbaCount; rgbaIndex += 1) { // If we are working with a 4 dimensional array, ignore the first dimension // DEV: This is a GIF; [frames, width, height, rgba] var val; if (img.shape.length === 4) { val = img.get(0, colIndex, rowIndex, rgbaIndex); // Otherwise, transfer data directly } else { val = img.get(colIndex, rowIndex, rgbaIndex); } ndarray.set(xOffset + colIndex, yOffset + rowIndex, rgbaIndex, val); } } } }); // Concatenate the ndarray into a png // TODO: We should start sending back streams savePixels(ndarray, ext).pipe(concat(function concatenateImage (buff) { cb(null, buff.toString('binary')); })); };
co(function*(){ var START = 640; var END = 3600; var GROWTH = END/START; var SAMPLE_SIZE = 2; var baseImg = yield getBasePixels("../sketch/test.jpg"); var endImg = ndarray([], [END, END, 3]); for(var x=0; x<END; x++){ var rowId = "row"; console.time(rowId); var distTime = 0; for(y=0; y<END; y++){ var mx = Math.floor(x / GROWTH); var my = Math.floor(y / GROWTH); var sx = Math.max(mx - SAMPLE_SIZE, 0); var ex = mx + SAMPLE_SIZE; var sy = Math.max(my - SAMPLE_SIZE, 0); var ey = my + SAMPLE_SIZE; var red = 0; var green = 0; var blue = 0; var count = 0; for(var cx=sx; cx<ex; cx++){ for(var cy=sy; cy<ey; cy++){ red += baseImg.get(cx,cy,0); green += baseImg.get(cx,cy,1); blue += baseImg.get(cx,cy,2); count++; } } endImg.set(x, y, 0, Math.floor(red / count)); endImg.set(x, y, 1, Math.floor(green / count)); endImg.set(x, y, 2, Math.floor(blue / count)); } console.log(x); console.timeEnd(rowId); } savePixels(endImg, "jpg").pipe(fs.createWriteStream("./sample-"+SAMPLE_SIZE+".jpg")); }).catch(function(err){
function handleResult (cb) { // If we received a non-zero exit code, complain and leave if (code !== 0) { var err = new Error('Received non-zero exit code "' + code + '" from PhantomJS. stdout:' + stdout); return cb(err); } // Otherwise, decode the pixel values // DEV: This used to be thinner and not need padding but Windows was messing up the image var encodedPixels = stdout; var decodedPixels; try { decodedPixels = JSON.parse(encodedPixels); } catch (e) { return cb(new Error('Error while parsing JSON "' + encodedPixels + '".\n' + e.message)); } // If we are dealing with a `jpeg`, then use `jpeg-js` // DEV: This is to support `quality` which `save-pixels` doesn't var resultStream; if (['jpg', 'jpeg'].indexOf(format) !== -1) { // Encode our data via `jpeg-js` and callback with its internal buffer var jpg; try { jpg = jpegJs.encode({ data: decodedPixels, width: params.width, height: params.height }, options.quality); } catch (err) { return cb(err); } resultStream = new ContentStream(jpg.data); // Otherwise, leverage `save-pixels` } else { // Convert the pixels into an ndarray // Taken from https://github.com/mikolalysenko/get-pixels/blob/2ac98645119244d6e52afcef5fe52cc9300fb27b/dom-pixels.js#L14 var imgNdarray = ndarray(decodedPixels, [params.height, params.width, 4], [4 * params.width, 4, 1], 0); // Generate our result stream resultStream = savePixels(imgNdarray, format); } // Pipe the stream into the returned result and handle errors resultStream.on('error', function forwardError (err) { retStream.emit('error', err); }); resultStream.pipe(retStream); }
it("should decode what it encoded", function(done) { const encode = dmCreator.generateDm({ data: "hello" }); var data = new Buffer(encode.pixels); var image = ndarray(encode.pixels, [encode.width, encode.height, encode.channels]) var output = fs.createWriteStream("test/output.png"); var stream = savePixels(image, "png").pipe(output); stream.on("finish", function() { getPixels("./test/output.png", function(err, pixels) { const res = decodePixels(err, pixels); res.success.should.be.true(); res.text.should.equal("hello"); done(); }); }); });
getPixels(img.src, (err, pixels) => { if (err) { return onerror(err, img); } // see https://en.wikipedia.org/wiki/HSL_color_space#HSV_.28Hue_Saturation_Value.29 if (this.colorMap === undefined) { this.colorMap = graycolorize.generateMap(120/360, 0.7); } graycolorize(pixels, this.colorMap); const img2 = new Image(); img2.src = savePixels(pixels, 'canvas').toDataURL(); img2.onload = () => onload(img2); img2.onerror = (err) => onerror(err, img2); });
read(file, function(err, data) { if (err) return next(err) var out = fs.createWriteStream(dest) save(convert(data), 'png') .pipe(out) .once('error', next) .once('close', function() { console.error('trimmed ' + file + '...') dest = path.relative(__dirname + '/..', dest) name = name.replace(/\.png/g, '') next(null, { uri: dest, name: name }) }) })
getPixels(tmp, function(err, pixels) { if(err) { console.log("Bad image path") return } var pxlArray = pixels.shape.slice() var secretz = lsb.decode(pixels.data, pickRGB) console.log(secretz) savePixels(pixels, "png").pipe(concat(function(png) { var dataUri = 'data:' + imgBuff.type + ';base64,' + png.toString('base64') req.body.content.data = dataUri req.body.content.type = imgBuff.type res.json(req.body) })) })
rawData.then(function (rawData) { var end = Date.now(); var duration = end - start; // Toss raw data back into pixels; offset = 0; for (var w = 0; w < width; w++) { for (var h = 0; h < height; h++ ) { for (var c = 0; c < channels; c++) { var val = rawData[offset]; pixels.set(w,h,c,val); offset++; } } } var stream = savePixels(pixels, "png"); toArray(stream, function (err, parts) { var buffers = []; for (var i = 0, l = parts.length; i < l ; ++i) { var part = parts[i]; buffers.push((part instanceof Buffer) ? part : new Buffer(part)); } var buf = Buffer.concat(buffers); var base64Encoded = buf.toString('base64'); var prefix = 'data:image/png;base64,'; var imageUrl = prefix + base64Encoded; res.render('index', { title: 'Edge Detection Demo', duration: String(duration) + ' ms to compute.', imageUrl: imageUrl, imageUrl2: 'http://localhost:3001/images/' + imgName }); }); });
function plotPredicate(pred) { var img = ndarray(new Uint8Array(NX*NY*3), [NX,NY,3]) for(var i=0; i<NX; ++i) { for(var j=0; j<NY; ++j) { var px = 0.5 + i * Math.pow(2, -53) var py = 0.5 + j * Math.pow(2, -53) var o = pred([px, py], [12, 12], [24, 24]) if(o < 0) { img.set(i,j,2,255) } else if(o > 0) { img.set(i,j,0,255) } else { img.set(i,j,1,255) } } } //imshow(img) return savePixels(img, "png") }
return new Promise(function(resolve, reject) { var imgStream = savePixels(pixels, "png"); var bufs = []; imgStream.on("data", function(d) { bufs.push(d); }); imgStream.on("end", function() { var buf = Buffer.concat(bufs); if (outFile) { fs.writeFile(outFile, buf, function(err) { if (err) { return reject(err); } resolve(buf); }); } else { resolve(buf); } }); });
getPixels(url, function(err, pixels) { /* manual test var colormap = ndarray(new Uint8Array(256*4), [256,4]); colormap.set(0x71, 0, 0x42); colormap.set(0x71, 1, 0x7f); colormap.set(0x71, 2, 0x13); colormap.set(0x71, 3, 0xff); */ //colormap = graycolorize.generateMap(0.25 /* 90deg(/360), green-yellow */, 0.5, 0.3, 1.0); colormap = graycolorize.generateMap(0.25, 0.5); console.log('colormap=',colormap); graycolorize(pixels, colormap); console.log(err, pixels); var canvas = savePixels(pixels, 'canvas'); canvas.style.width = canvas.style.height = size + 'px'; canvasContainer.appendChild(canvas); });
var saveImage = function(pixels, imgId){ savePixels(pixels, "jpg").pipe(fs.createWriteStream("./data/"+imgId+".jpg")); return new Promise(function(resolve){ setTimeout(resolve, 200); }); }
co(function*(){ var numImgs = listOfImages.length; var SHIFT_WEIGHT = 1/16; var trainData = []; for(var b=1; b<numImgs; b++){ var imgId = listOfImages[b]; var imgPath = path.join(__dirname, "../../instagrams", imgId+".jpg"); console.log("parse "+imgPath+" "+b+" of "+numImgs); var img = yield getBasePixels(imgPath); var fork = pattern(640); var next = fork.next(); var current = []; while(next.done === false){ var x = next.value[0]; var y = next.value[1]; var red = Math.floor(img.get(x, y, 0) / 16) * SHIFT_WEIGHT; var green = Math.floor(img.get(x, y, 1) / 16) * SHIFT_WEIGHT; var blue = Math.floor(img.get(x, y, 2) / 16) * SHIFT_WEIGHT; current.push(red); current.push(green); current.push(blue); if(current.length === BLOCK_SIZE){ trainData.push([current, current]); current = []; } next = fork.next(); } } console.log("Train!", trainData.length); var net = new fann.standard(BLOCK_SIZE, 16, BLOCK_SIZE); // net.training_algorithm = "INCREMENTAL"; // net.learning_momentum = .2; // net.learning_rate = .5; console.log("training_algorithm", net.training_algorithm); console.log("learning_rate", net.learning_rate); console.log("learning_momentum", net.learning_momentum); var info = net.train(trainData, {error: 0.005, epochs_between_reports: 10}); var imgId = listOfImages[0]; var imgPath = path.join(__dirname, "../../instagrams", imgId+".jpg"); var img = yield getBasePixels(imgPath); var pixels = ndarray([], [640, 640, 3]); for(var trip=1; trip<ITTERATIONS+1; trip++){ console.log("start", trip); var fork = pattern(640); var next = fork.next(); var p = 0; var data = []; var get = []; var xy = []; while(next.done === false){ var x = next.value[0]; var y = next.value[1]; var red = Math.floor(img.get(x, y, 0) / 16) * SHIFT_WEIGHT; var green = Math.floor(img.get(x, y, 1) / 16) * SHIFT_WEIGHT; var blue = Math.floor(img.get(x, y, 2) / 16) * SHIFT_WEIGHT; get.push(red); get.push(green); get.push(blue); xy.push({ x: x, y: y }); if(get.length == BLOCK_SIZE){ var data = net.run(get); for(var i=0; i<xy.length; i++){ var xx = xy[i].x; var yy = xy[i].y; var j = i*3; for(var k=0; k<3; k++){ var val = Math.floor((data[j+k] / SHIFT_WEIGHT) * 16); pixels.set(xx, yy, k, val); } } get = []; xy = []; } next = fork.next(); } if(trip%20 === 0 || trip === 1 || trip === ITTERATIONS){ console.log("saving this one"); var tripStub = trip - 10 < 0 ? "00"+trip : trip - 100 < 0 ? "0"+trip : trip; savePixels(pixels, "jpg").pipe(fs.createWriteStream("./imgs/"+tripStub+".jpg")); } img = pixels; } }).then(sketchSaver).catch(function(err){
before(function (done) { var png = savePixels(ndarray(this.actualPixels, [10, 10, 4], [4 * 10, 4, 1], 0), 'png'); try { fs.mkdirSync(__dirname + '/actual-files'); } catch (e) {} png.pipe(fs.createWriteStream(__dirname + '/actual-files/' + filename)); png.on('end', done); });
co(function*(){ var IMG_SIZE = 640; var numImgs = listOfImages.length; var imgLength = IMG_SIZE * IMG_SIZE; var fivePercent = imgLength/20; var pixels = ndarray([], [IMG_SIZE, IMG_SIZE, 3]); var imgs = []; for(var b=0; b<numImgs; b++){ var imgId = listOfImages[b]; var imgPath = path.join(__dirname, "../../instagrams", imgId+".jpg"); console.log("parse "+imgPath+" "+b+" of "+numImgs); console.time("report"); var img = yield getBasePixels(imgPath); imgs.push(img); } var fork = pattern(IMG_SIZE); var next = fork.next(); while(next.done === false){ var x = next.value[0]; var y = next.value[1]; var redTotal = 0; var greenTotal = 0; var blueTotal = 0; var maxTotal = 0; var midTotal = 0; for(var i=0; i<numImgs; i++){ var colors = getColors(imgs[i], x, y); redTotal = redTotal + colors.red; greenTotal = greenTotal + colors.green; blueTotal = blueTotal + colors.blue; var max = Math.max(colors.red, colors.green, colors.blue); var mid = [colors.red, colors.green, colors.blue].sort()[1]; maxTotal = maxTotal + max; midTotal = midTotal + mid; } var dist = [ { value: redTotal, channel: 0 }, { value: greenTotal, channel: 1 }, { value: blueTotal, channel: 2 } ]; dist.sort(function(a, b){ return a.value - b.value; }); var maxAvg = Math.floor(maxTotal / numImgs); var midAvg = Math.floor(midTotal / numImgs); var min = Math.floor(dist[2].value / numImgs); pixels.set(x, y, dist[0].channel, maxAvg); pixels.set(x, y, dist[1].channel, midAvg); pixels.set(x, y, dist[2].channel, min); next = fork.next(); } console.log("writing"); savePixels(pixels, "jpg").pipe(fs.createWriteStream("./test.jpg")); }).then(sketchSaver).catch(function(err){
co(function*(){ var BLOCK_SIZE = 12; var NUM_COLORS = 256; var BACK_TRACK = 2; var mash = function(a){ var out = 0; for(var i=0; i<a.length; i++){ out += a[i] } return out; } var numImgs = listOfImages.length; var records = []; for(var b=1; b<numImgs; b++){ var imgId = listOfImages[b]; var imgPath = path.join(__dirname, "../../instagrams", imgId+".jpg"); console.log("parse "+imgPath+" "+b+" of "+numImgs); var img = yield getBasePixels(imgPath); var result = groupCrome([img], NUM_COLORS, BLOCK_SIZE, function(a){ return mash(a)+"-" }, 20, 20); savePixels(result.imgs[0], "jpg").pipe(fs.createWriteStream("./imgs/"+imgId+".jpg")); records.push(result.colors); } var getColor = function(block){ var scores = [scoreGroup(block, records[0])]; var min = getMin(scores[0]); var minIndex = 0; for(var i=1; i<records.length; i++){ scores.push(scoreGroup(block, records[i])); var pm = getMin(scores[i]); if(pm < min){ min = pm; minIndex = i; } } var minScore = scores[minIndex]; var posOfMin = minScore.indexOf(min); var nextColor = records[minIndex][posOfMin]; return nextColor; } console.log("loading new img"); var newImg = yield getBasePixels(path.join(__dirname, "../../instagrams", listOfImages[0]+".jpg")); var fork = pattern(640); var next = fork.next(); var current = []; var xys = []; while(next.done === false){ var x = next.value[0]; var y = next.value[1]; xys = xys.concat([[x,y]]); var red = newImg.get(x, y, 0); var green = newImg.get(x, y, 1); var blue = newImg.get(x, y, 2); current = current.concat([red, green, blue]); if(xys.length == BLOCK_SIZE){ var color = getColor(current); for(var i=0; i<BACK_TRACK; i++){ var x = xys[0][0]; var y = xys[0][1]; newImg.set(x, y, 0, color[0]); newImg.set(x, y, 1, color[1]); newImg.set(x, y, 2, color[2]); xys = xys.splice(1); current = color.splice(3); } } var next = fork.next(); } console.log("image built"); savePixels(newImg, "jpg").pipe(fs.createWriteStream("./imgs/new.jpg")); }).then(sketchSaver).catch(function(err){
co(function*(){ var IMG_SIZE = 640; var numImgs = listOfImages.length; var imgLength = IMG_SIZE * IMG_SIZE; var fivePercent = imgLength/20; var pixels = ndarray([], [IMG_SIZE, IMG_SIZE, 3]); var imgs = []; for(var b=0; b<numImgs; b++){ var imgId = listOfImages[b]; var imgPath = path.join(__dirname, "../../instagrams", imgId+".jpg"); console.log("parse "+imgPath+" "+b+" of "+numImgs); console.time("report"); var img = yield getBasePixels(imgPath); imgs.push(img); } var fork = pattern(IMG_SIZE); var mind = {}; var ids = []; var loc = null; var last = fork.next(); var item = fork.next(); var p = 0; var lastReport = 0; console.log("teaching"); while(item.done === false){ for(var i=0; i<numImgs; i++){ var pixel = getColors(imgs[i], last.value[0], last.value[1], p); var next = getColors(imgs[i], item.value[0], item.value[1], p+1); pixel.dist = Math.abs(pixel.green - next.green); pixel.next = next.id; if(loc === null){ loc = pixel.id; } if(mind[pixel.id] === undefined){ mind[pixel.id] = { vals: [], pos: 0 }; ids.push(pixel.id); } mind[pixel.id].vals.push(pixel); } last = item; item = fork.next(); p++; if(p>lastReport+fivePercent){ console.log((100/imgLength)*p); lastReport = p; } } for(var i=0; i<numImgs; i++){ var pixel = getColors(imgs[i], last.value[0], last.value[1], p+1); var next = getColors(imgs[i], last.value[0], last.value[1], p+1); pixel.dist = Math.abs(pixel.green - next.green); pixel.next = next.id; if(mind[pixel.id] === undefined){ mind[pixel.id] = { vals: [], pos: 0 }; ids.push(pixel.id); } mind[pixel.id].vals.push(pixel); } console.log("sorting"); for(var i=0; i<ids.length; i++){ var id = ids[i]; mind[id].vals.sort(function(a, b){ return b.dist - a.dist; }); } var fork = pattern(IMG_SIZE); var cur = fork.next(); var p = 0; var lastReport = 0; var used = {}; var usedIds = []; var reset = 0; console.log("filling in pixels"); while(cur.done === false){ used[loc] = used[loc] ? used[loc] + 1 : 1; if(used[loc]){ used[loc] = used[loc] + 1; } else{ used[loc] = 1; usedIds.push(loc); } var x = cur.value[0]; var y = cur.value[1]; try{ var pixel = mind[loc].vals[mind[loc].pos]; mind[loc].pos = mind[loc].pos + 1; if(mind[loc].pos == mind[loc].vals.length){ mind[loc].pos = 0; reset++; } pixels.set(x, y, 0, pixel.red); pixels.set(x, y, 1, pixel.green); pixels.set(x, y, 2, pixel.blue); } catch(err){ pixels.set(x, y, 0, 0); pixels.set(x, y, 1, 0); pixels.set(x, y, 2, 255); } oldLoc = loc; loc = pixel.next; cur = fork.next(); p++; if(p>lastReport+fivePercent){ console.log((100/imgLength)*p); lastReport = p; } } console.log("analyzing"); var perIdsUsed = (100/ids.length)*usedIds.length; console.log("perIdsUsed", perIdsUsed); var perReset = (100/imgLength)*reset; console.log("perReset", perReset); console.log("writing"); savePixels(pixels, "jpg").pipe(fs.createWriteStream("./test.jpg")); }).then(sketchSaver).catch(function(err){
co(function*(){ var BLOCK_SIZE = 6; var NUM_COLORS = 2; var mash = function(a){ return Math.floor(Math.max.apply(null, a) / 16) * 16; } var numImgs = listOfImages.length; var records = []; for(var b=0; b<numImgs; b++){ var imgId = listOfImages[b]; var imgPath = getPath(imgId); console.log("parse "+imgPath+" "+b+" of "+numImgs); var img = yield getBasePixels(imgPath); var result = groupCrome([img], NUM_COLORS, BLOCK_SIZE, function(a){ return mash(a)+"-" }); savePixels(result.imgs[0], "jpg").pipe(fs.createWriteStream("./imgs/"+imgId+".jpg")); records.push(result.colors); } var getColor = function(block){ var scores = [scoreGroup(block, records[0])]; var min = getMin(scores[0]); var minIndex = 0; for(var i=1; i<records.length; i++){ scores.push(scoreGroup(block, records[i])); var pm = getMin(scores[i]); if(pm < min){ min = pm; minIndex = i; } } var minScore = scores[minIndex]; var posOfMin = minScore.indexOf(min); var nextColor = records[minIndex][posOfMin]; return nextColor; } for(var k=0; k<others.length; k++){ var imgId = others[k]; console.log("loading new img"); var newImg = yield getBasePixels(getPath(imgId)); var fork = pattern(640); var next = fork.next(); var current = []; var xys = []; while(next.done === false){ var x = next.value[0]; var y = next.value[1]; xys = xys.concat([[x,y]]); var red = newImg.get(x, y, 0); var green = newImg.get(x, y, 1); var blue = newImg.get(x, y, 2); current = current.concat([red, green, blue]); if(xys.length == BLOCK_SIZE){ var color = getColor(current); for(var i=0; i<BLOCK_SIZE; i++){ var x = xys[i][0]; var y = xys[i][1]; var j = i*3 newImg.set(x, y, 0, color[j+0]); newImg.set(x, y, 1, color[j+1]); newImg.set(x, y, 2, color[j+2]); } current = []; xys = []; } var next = fork.next(); } console.log("image built", imgId); savePixels(newImg, "jpg").pipe(fs.createWriteStream("./others/"+imgId+".jpg")); } }).then(sketchSaver).catch(function(err){
var fs = require("fs") var savePixels = require("save-pixels") var baboon = require("luminance")(require("baboon-image")) var patch = baboon.lo(222, 215).hi(80, 80) savePixels(baboon, "png").pipe(fs.createWriteStream(__dirname + "/baboon.png")) savePixels(patch, "png").pipe(fs.createWriteStream(__dirname + "/patch.png")) var position = require("../align.js")(patch, baboon) console.log(position)
co(function*(){ var numImgs = listOfImages.length; var trainData = []; var SHIFT_WEIGHT = 1/256; var BLOCK_SIZE = parseInt(process.argv[2]); console.log("BLOCK_SIZE:", BLOCK_SIZE); for(var b=1; b<numImgs; b++){ var imgId = listOfImages[b]; var imgPath = path.join(__dirname, "../../instagrams", imgId+".jpg"); console.log("parse "+imgPath+" "+b+" of "+numImgs); var img = yield getBasePixels(imgPath); var fork = pattern(640); var next = fork.next(); var current = []; while(next.done === false){ var x = next.value[0]; var y = next.value[1]; var red = img.get(x, y, 0); var green = img.get(x, y, 1); var blue = img.get(x, y, 2); current.push(red * SHIFT_WEIGHT); current.push(green * SHIFT_WEIGHT); current.push(blue * SHIFT_WEIGHT); if(current.length === BLOCK_SIZE * 3){ trainData.push({input:current, output:current}); current = []; } next = fork.next(); } } console.log("Train!", trainData.length); var net = new brain.NeuralNetwork({ hiddenLayers: [3, 2, 1] }); var info = net.train(trainData, { errorThresh: 0.005, // error threshold to reach iterations: 2000, // maximum training iterations log: true, // console.log() progress periodically logPeriod: 20, // number of iterations between logging learningRate: 0.1 // learning rate }); console.log("TRAINING INFO", info); var imgId = listOfImages[0]; var imgPath = path.join(__dirname, "../../instagrams", imgId+".jpg"); var img = yield getBasePixels(imgPath); var pixels = ndarray([], [640, 640, 3]); console.log("start"); var fork = pattern(640); var next = fork.next(); var p = 0; var data = []; var get = []; var xy = []; while(next.done === false){ var x = next.value[0]; var y = next.value[1]; var red = img.get(x, y, 0); var green = img.get(x, y, 1); var blue = img.get(x, y, 2); get.push(red * SHIFT_WEIGHT); get.push(green * SHIFT_WEIGHT); get.push(blue * SHIFT_WEIGHT); xy.push({ x: x, y: y }); if(get.length == BLOCK_SIZE * 3){ var data = net.run(get); for(var i=0; i<BLOCK_SIZE; i++){ var xx = xy[i].x; var yy = xy[i].y; var start = i*3; pixels.set(xx, yy, 0, Math.floor(data[start] / SHIFT_WEIGHT)); pixels.set(xx, yy, 1, Math.floor(data[start+1] / SHIFT_WEIGHT)); pixels.set(xx, yy, 2, Math.floor(data[start+2] / SHIFT_WEIGHT)); } get = []; xy = []; } next = fork.next(); } console.log("end"); var stub = BLOCK_SIZE - 10 < 0 ? "00"+BLOCK_SIZE : BLOCK_SIZE - 100 < 0 ? "0"+BLOCK_SIZE : BLOCK_SIZE; savePixels(pixels, "jpg").pipe(fs.createWriteStream("./"+stub+".jpg")); }).then(sketchSaver).catch(function(err){