Skip to content

Instantly share code, notes, and snippets.

@brysgo
Last active November 6, 2018 22:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brysgo/d430790f230289f2201e06355f4d3336 to your computer and use it in GitHub Desktop.
Save brysgo/d430790f230289f2201e06355f4d3336 to your computer and use it in GitHub Desktop.
Convert via region data to yolo format
const fs = require("fs");
const path = require("path");
const sizeOf = require("image-size");
const args = process.argv.slice(2);
const data = require(path.join(path.resolve(args[0]), "/via_region_data.json"));
const imgMetadata = Object.values(data["_via_img_metadata"]);
const firstFour = list => list.slice(0, 4);
const sum = list => list.reduce((acc, cur) => acc + cur, 0);
const average = list => Math.round(sum(list) / list.length);
const xListYListToCenterXYHeightWidth = (xList, yList) => {
const centerX = average(xList);
const centerY = average(yList);
const maxX = Math.max(...xList);
const maxY = Math.max(...yList);
const minX = Math.min(...xList);
const minY = Math.min(...yList);
const width = maxX - minX;
const height = maxY - minY;
return { centerX, centerY, width, height };
};
imgMetadata.forEach(({ filename, regions }) => {
const dimensions = sizeOf(path.join(path.resolve(args[0]), filename));
fs.writeFile(
path.join(path.resolve(args[0]), filename.split(".")[0] + ".txt"),
regions
.map(({ shape_attributes }) => {
const firstFourX = firstFour(shape_attributes.all_points_x);
const firstFourY = firstFour(shape_attributes.all_points_y);
const {
centerX,
centerY,
width,
height
} = xListYListToCenterXYHeightWidth(firstFourX, firstFourY);
return [
1,
centerX / dimensions.width,
centerY / dimensions.height,
width / dimensions.width,
height / dimensions.height
].join(" ");
})
.join("\n"),
function(err) {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
}
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment