Created
January 12, 2015 07:12
-
-
Save mshr-h/bf34df3bb473770ebffe to your computer and use it in GitHub Desktop.
This file contains 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
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