Debian Codegraph @

writer/standard/imgkit/process.go

raw
1 package imgkit
2
3 import (
4 "image"
5 "image/color"
6
7 "golang.org/x/image/draw"
8 )
9
10 // Binaryzation process image with threshold value (0-255) and return new image.
11 func Binaryzation(src image.Image, threshold uint8) image.Image {
12 if threshold < 0 || threshold > 255 {
13 threshold = 128
14 }
15
16 gray := Gray(src)
17 bounds := src.Bounds()
18 height, width := bounds.Max.Y-bounds.Min.Y, bounds.Max.X-bounds.Min.X
19
20 for i := 0; i < height; i++ {
21 for j := 0; j < width; j++ {
22 // var rgb int = int(gray[i][j][0]) + int(gray[i][j][1]) + int(gray[i][j][2])
23 if gray.At(j, i).(color.Gray).Y > threshold {
24 gray.Set(j, i, color.White)
25 } else {
26 gray.Set(j, i, color.Black)
27 }
28 }
29 }
30
31 return gray
32 }
33
34 func Gray(src image.Image) *image.Gray {
35 bounds := src.Bounds()
36 height, width := bounds.Max.Y-bounds.Min.Y, bounds.Max.X-bounds.Min.X
37 gray := image.NewGray(bounds)
38
39 for i := 0; i < height; i++ {
40 for j := 0; j < width; j++ {
41 c := color.GrayModel.Convert(src.At(j, i))
42 gray.SetGray(j, i, c.(color.Gray))
43 }
44 }
45
46 return gray
47 }
48
49 func Scale(src image.Image, rect image.Rectangle, scale draw.Scaler) image.Image {
50 if scale == nil {
51 scale = draw.ApproxBiLinear
52 }
53
54 dst := image.NewRGBA(rect)
55 scale.Scale(dst, rect, src, src.Bounds(), draw.Over, nil)
56 return dst
57 }