Skip to content

Instantly share code, notes, and snippets.

@mshr-h
Created January 12, 2015 07:12
Show Gist options
  • Save mshr-h/bf34df3bb473770ebffe to your computer and use it in GitHub Desktop.
Save mshr-h/bf34df3bb473770ebffe to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"image"
"image/color"
"image/png"
"log"
"os"
)
func main() {
var inFile *os.File
var outFile *os.File
var img image.Image
var err error
if len(os.Args) < 2 {
log.Fatal()
}
for i := 1; i < len(os.Args); i++ {
filename := os.Args[i]
if inFile, err = os.Open(filename); err != nil {
log.Fatal(err)
}
if img, err = png.Decode(inFile); err != nil {
log.Fatal(err)
}
defer inFile.Close()
out_filename := "bin_" + filename[0:len(filename)-4] + ".png"
if outFile, err = os.Create(out_filename); err != nil {
log.Fatal(err)
}
img = binarize(&img, 100, 255, 0)
if err = png.Encode(outFile, img); err != nil {
fmt.Println()
return
}
}
}
func binarize(in *image.Image, th, th_h, th_l uint32) image.Image {
rect := (*in).Bounds()
out := image.NewGray(rect)
for h := 0; h < rect.Max.X; h++ {
for w := 0; w < rect.Max.Y; w++ {
c := (*in).At(h, w)
pel, _, _, _ := c.RGBA()
pel = pel >> 8
if pel > th {
pel = th_h
} else {
pel = th_l
}
out.Set(h, w, color.Gray{uint8(pel)})
}
}
return out
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment