Skip to content

Instantly share code, notes, and snippets.

@jsdf
Last active February 7, 2019 04:22
Show Gist options
  • Save jsdf/80cadb9d2a9b52517c116e282bc22d54 to your computer and use it in GitHub Desktop.
Save jsdf/80cadb9d2a9b52517c116e282bc22d54 to your computer and use it in GitHub Desktop.
utils to break images into tiles, crop and flip them
var gm = require('gm');
var glob = require('glob');
var path = require('path');
var fs = require('fs');
const labels = [];
function pathWithSuffix(inpath, suffix) {
return path.join(path.dirname(inpath),path.basename(inpath,'.jpg')+suffix+'.jpg');
}
function makeCropped(inpath, outpath,width,height,x,y) {
return new Promise((resolve,reject) => {
gm(inpath).crop(width,height,x,y).write(outpath, function (err) {
if (err) return reject(new Error('makeCropped'+ outpath+err));
resolve();
});
})
}
function makeFlopped(inpath, outpath) {
return new Promise((resolve, reject) => {
gm(inpath).flop().write(outpath, function (err) {
if (err) return reject(new Error('makeFlopped'+ outpath+err));
resolve();
});
})
}
function removeFile(inpath) {
return new Promise((resolve, reject) =>
fs.unlink(inpath, (err) => err?reject(err):resolve())
);
}
function copyFile(inpath,outpath) {
return new Promise((resolve, reject) => {
const out = fs.createWriteStream(outpath);
out.on('close', resolve);
out.on('error', reject);
fs.createReadStream(inpath).pipe(out);
});
}
function makeTiles(inpath, inwidth, inheight, n) {
let promises = [];
for (var row = 0; row < n; row++) {
for (var col = 0; col < n; col++) {
const tileoutpath = pathWithSuffix(inpath, `[${row}-${col}]`);
promises.push(
// crop tile for row and column
makeCropped(inpath, tileoutpath, inwidth/n, inheight/n, inwidth/n*col, inheight/n*row)
.then(() => {
console.log('done', tileoutpath)
})
);
}
}
return Promise.all(promises);
}
async function processImage(imagepath) {
const label = (path.basename(imagepath).includes('no')?'no':'yes');
const outpath = path.resolve(path.dirname(imagepath), '../prepared/',label+'-'+path.basename(imagepath));
labels.push([path.basename(imagepath),(path.basename(imagepath).includes('no')?'no':'yes')]);
console.log('outputting to', outpath);
await makeCropped(imagepath, outpath,1920, 980, 0, 32);
const allPaths = [outpath];
const floppedPath = pathWithSuffix(outpath, '-flopped');
await makeFlopped(outpath, floppedPath);
allPaths.push(floppedPath);
await Promise.all(allPaths.map(async p => {
await makeTiles(p, 1920, 980, 3);
await copyFile(p, pathWithSuffix(p, 'whole'));
await removeFile(p);
}));
console.log('done',allPaths)
}
Promise.all(glob.sync('./unprocessed/*.jpg').map(image =>
processImage(image)
.catch(err => {
console.error(err);
process.exit(1);
})
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment