Skip to content

Instantly share code, notes, and snippets.

@dmbfm
Created January 31, 2021 22:41
Show Gist options
  • Save dmbfm/da08b6539512f564e88dc8d0621edf0b to your computer and use it in GitHub Desktop.
Save dmbfm/da08b6539512f564e88dc8d0621edf0b to your computer and use it in GitHub Desktop.
B/w thresholding of a png image using Go
package main
import (
"fmt"
"image"
"image/color"
"image/png"
"os"
)
func Treshold(img image.Image, t float32) image.Image {
result := image.NewGray(img.Bounds())
for y := img.Bounds().Min.Y; y < img.Bounds().Max.Y; y++ {
for x := img.Bounds().Min.X; x < img.Bounds().Max.X; x++ {
r, g, b, _ := img.At(x, y).RGBA()
v := float32(uint8((r + g + b) / 3)) / 255.0
var final uint8
if v > t {
final = 255
} else {
final = 0
}
result.Set(x, y, color.Gray{ final })
}
}
return result
}
func main() {
r, err := os.Open("image.png")
if err != nil {
panic(err)
}
img, err := png.Decode(r)
if err != nil {
panic(err)
}
out := Treshold(img, 0.6)
w, err := os.Create("out.png")
if err != nil {
panic(err)
}
err = png.Encode(w, out)
if err != nil {
panic(err)
}
fmt.Println("Dither")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment