Last active
November 6, 2018 22:53
-
-
Save brysgo/d430790f230289f2201e06355f4d3336 to your computer and use it in GitHub Desktop.
Convert via region data to yolo format
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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