Skip to content

Instantly share code, notes, and snippets.

@pgundlach
Created September 2, 2016 07:21
Show Gist options
  • Save pgundlach/218d45700548309c18299f56f9984252 to your computer and use it in GitHub Desktop.
Save pgundlach/218d45700548309c18299f56f9984252 to your computer and use it in GitHub Desktop.
Extract the image shape to use with the speedata Publisher
package main
import (
"encoding/xml"
"fmt"
"image"
"image/color"
"log"
"os/exec"
_ "image/png"
)
type Imageinfo struct {
XMLName xml.Name `xml:"imageinfo"`
CellsX int `xml:"cells_x"`
CellsY int `xml:"cells_y"`
Segment []Segment
}
type Segment struct {
XMLName xml.Name `xml:"segment"`
X1 int `xml:"x1,attr"`
X2 int `xml:"x2,attr"`
Y1 int `xml:"y1,attr"`
Y2 int `xml:"y2,attr"`
}
func isBlack(col color.Color) bool {
switch x := col.(type) {
case color.Gray16:
return x.Y < 0xfa00
default:
log.Fatal("Unknown type for color %#v", col)
}
return true
}
func main() {
imagepath := "pocketwatch.pdf"
// Run imagemagick to get a max(40x40) pixel image
cmd := exec.Command("convert", imagepath, "-monochrome", "-resize", "40x40", "png:-")
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Fatal(err)
}
err = cmd.Start()
if err != nil {
log.Fatal(err)
}
img, _, err := image.Decode(stdout)
if err != nil {
log.Fatal(err)
}
err = cmd.Wait()
if err != nil {
log.Fatal(err)
}
// Now construct the XML
bounds := img.Bounds()
ii := Imageinfo{}
ii.CellsX = bounds.Dx()
ii.CellsY = bounds.Dy()
for y := 0; y < bounds.Dy(); y++ {
s := Segment{}
hasBlackPixel := false
for x := 0; x < bounds.Dx(); x++ {
s.Y1 = y + 1
s.Y2 = y + 1
if isBlack(img.At(x, y)) {
hasBlackPixel = true
if s.X1 == 0 {
s.X1 = x + 1
}
s.X2 = x + 1
}
}
if hasBlackPixel {
ii.Segment = append(ii.Segment, s)
}
}
b, err := xml.MarshalIndent(ii, "", " ")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(b))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment