summaryrefslogtreecommitdiff
path: root/binarize/util.go
blob: e7cf0f8dc2abdbab27ac1d0933389e2c418db9cd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main

import (
	"image"
	"math"
)

func mean(i []int) float64 {
	sum := 0
	for _, n := range i {
		sum += n
	}
	return float64(sum) / float64(len(i))
}

func stddev(i []int) float64 {
	m := mean(i)

	var sum float64
	for _, n := range i {
		sum += (float64(n) - m) * (float64(n) - m)
	}
	variance := sum / float64(len(i) - 1)
	return math.Sqrt(variance)
}

func meanstddev(i []int) (float64, float64) {
	m := mean(i)

	var sum float64
	for _, n := range i {
		sum += (float64(n) - m) * (float64(n) - m)
	}
	variance := float64(sum) / float64(len(i) - 1)
	return m, math.Sqrt(variance)
}

// gets the pixel values surrounding a point in the image
func surrounding(img *image.Gray, x int, y int, size int) []int {
	b := img.Bounds()
	step := size / 2

	miny := y - step
	if miny < b.Min.Y {
		miny = b.Min.Y
	}
	minx := x - step
	if minx < b.Min.X {
		minx = b.Min.X
	}
	maxy := y + step
	if maxy > b.Max.Y {
		maxy = b.Max.Y
	}
	maxx := x + step
	if maxx > b.Max.X {
		maxx = b.Max.X
	}

	var s []int
	for yi := miny; yi <= maxy; yi++ {
		for xi := minx; xi <= maxx; xi++ {
			s = append(s, int(img.GrayAt(xi, yi).Y))
		}
	}
	return s
}