Created
January 31, 2021 22:53
-
-
Save dmbfm/afa481063f334b661239aba78626e9ac 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" | |
"math" | |
"os" | |
) | |
func Treshold(img image.Image, t float32) (image.Image, image.Image) { | |
result := image.NewGray(img.Bounds()) | |
qerr := 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 }) | |
delta := math.Abs(float64(final) - float64(255.0 * v)) | |
qerr.Set(x, y, color.Gray{ uint8(delta) }) | |
} | |
} | |
return result, qerr | |
} | |
func main() { | |
r, err := os.Open("image.png") | |
if err != nil { | |
panic(err) | |
} | |
img, err := png.Decode(r) | |
if err != nil { | |
panic(err) | |
} | |
out, qerr := Treshold(img, 0.6) | |
w, err := os.Create("out.png") | |
if err != nil { | |
panic(err) | |
} | |
w2, err := os.Create("qerr.png") | |
if err != nil { | |
panic(err) | |
} | |
err = png.Encode(w, out) | |
err = png.Encode(w2, qerr) | |
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