-
Notifications
You must be signed in to change notification settings - Fork 8
/
epub_image_filters_autocontrast.go
90 lines (76 loc) · 2.18 KB
/
epub_image_filters_autocontrast.go
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package epubimagefilters
import (
"image"
"image/color"
"image/draw"
"github.com/disintegration/gift"
)
// AutoContrast Automatically improve contrast
func AutoContrast() gift.Filter {
return &autocontrast{}
}
type autocontrast struct {
}
// compute the color number between 0 and 1 that hold half of the pixel
func (f *autocontrast) mean(src image.Image) float32 {
bucket := map[int]int{}
for x := src.Bounds().Min.X; x < src.Bounds().Max.X; x++ {
for y := src.Bounds().Min.Y; y < src.Bounds().Max.Y; y++ {
v, _, _, _ := color.GrayModel.Convert(src.At(x, y)).RGBA()
bucket[int(v)]++
}
}
// calculate color idx
var colorIdx int
{
// limit to half of the pixel
limit := src.Bounds().Dx() * src.Bounds().Dy() / 2
// loop on all color from 0 to 65536
for colorIdx := range 1 << 16 {
if limit-bucket[colorIdx] < 0 {
break
}
limit -= bucket[colorIdx]
}
}
// return the color idx between 0 and 1
return float32(colorIdx) / (1 << 16)
}
// ensure value stay into 0 to 1 bound
func (f *autocontrast) cap(v float32) float32 {
if v < 0 {
return 0
}
if v > 1 {
return 1
}
return v
}
// power of 2 for float32
func (f *autocontrast) pow2(v float32) float32 {
return v * v
}
// Draw into the dst after applying the filter
func (f *autocontrast) Draw(dst draw.Image, src image.Image, options *gift.Options) {
// half of the pixel has this color idx
colorMean := f.mean(src)
// if colorMean > 0.5, it means the color is mostly clear
// in that case we will add a lot more darkness other light
// compute dark factor
d := f.pow2(colorMean)
// compute light factor
l := f.pow2(1 - colorMean)
gift.ColorFunc(func(r0, g0, b0, a0 float32) (r float32, g float32, b float32, a float32) {
// convert to gray color the source RGB
y := 0.299*r0 + 0.587*g0 + 0.114*b0
// compute a curve from dark and light factor applying to the color
c := (1 - d) + (d+l)*y
// applying the ratio
return f.cap(r0 * c), f.cap(g0 * c), f.cap(b0 * c), a0
}).Draw(dst, src, options)
}
// Bounds calculates the appropriate bounds of an image after applying the filter.
func (*autocontrast) Bounds(srcBounds image.Rectangle) (dstBounds image.Rectangle) {
dstBounds = srcBounds
return
}