Skip to content

Instantly share code, notes, and snippets.

@hiepph
Created May 27, 2020 09:51
Show Gist options
  • Save hiepph/06627329652ac8f839b70313ea3a59ac to your computer and use it in GitHub Desktop.
Save hiepph/06627329652ac8f839b70313ea3a59ac to your computer and use it in GitHub Desktop.
LabelMe xml to csv
package main
import (
"encoding/xml"
"fmt"
"io/ioutil"
"os"
)
type Annotation struct {
XMLName xml.Name `xml:"annotation"`
Filename string `xml:"filename"`
Objects []Object `xml:"object"`
}
type Object struct {
XMLName xml.Name `xml:"object"`
Name string `xml:"name"`
Polygon Polygon `xml:"polygon"`
}
type Polygon struct {
XMLName xml.Name `xml:"polygon"`
// Username string `xml:"username"`
Points []Point `xml:"pt"`
}
type Point struct {
XMLName xml.Name `xml:"pt"`
X int32 `xml:"x"`
Y int32 `xml:"y"`
}
func main() {
files, err := ioutil.ReadDir("./Annotations")
if err != nil {
panic(err)
}
f, err := os.Create("template.csv")
if err != nil {
panic(err)
}
defer f.Close()
// fmt.Fprintf(f, "image_name,x0_pos,y0_pos,x1_pos,y1_pos,class\n")
for _, fn := range files {
fp := fmt.Sprintf("Annotations/%s", fn.Name())
xmlFile, err := os.Open(fp)
defer xmlFile.Close()
if err != nil {
panic(err)
}
byteValue, _ := ioutil.ReadAll(xmlFile)
var anno Annotation
xml.Unmarshal(byteValue, &anno)
for _, object := range anno.Objects {
fmt.Fprintf(f, "%s,%d,%d,%d,%d,%s\n",
anno.Filename,
object.Polygon.Points[0].X,
object.Polygon.Points[0].Y,
object.Polygon.Points[2].X,
object.Polygon.Points[2].Y,
object.Name,
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment