-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
113 lines (101 loc) · 2.43 KB
/
main.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
// Copyright 2022 The Entropy Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"image"
"image/color"
"image/png"
"log"
"math/cmplx"
"math/rand"
"os"
"sort"
"github.com/mjibson/go-dsp/fft"
)
func main() {
os.MkdirAll("gray", 0755)
Process("image01")
Process("image02")
Process("image03")
Process("image04")
}
// Entropy returns the entropy of the given image
func Entropy(x [][]complex128) complex128 {
var factor complex128
for _, r := range x {
for _, c := range r {
a := complex(cmplx.Abs(c), 0)
factor += a * a
}
}
factor = cmplx.Sqrt(factor)
var sum complex128
for _, r := range x {
for _, c := range r {
c /= factor
sum += c * cmplx.Log(c)
}
}
return -sum
}
func Process(name string) {
fmt.Println(name)
rnd := rand.New(rand.NewSource(1))
input, err := os.Open(fmt.Sprintf("images/%s.png", name))
if err != nil {
log.Fatal(err)
}
defer input.Close()
img, err := png.Decode(input)
if err != nil {
panic(err)
}
b := img.Bounds()
set := image.NewRGBA(b)
xx := make([][]complex128, b.Max.Y)
zz := make([]uint8, b.Max.Y*b.Max.X)
for y := 0; y < b.Max.Y; y++ {
xx[y] = make([]complex128, b.Max.X)
for x := 0; x < b.Max.X; x++ {
original := img.At(x, y)
pixel := color.GrayModel.Convert(original)
gray, _ := pixel.(color.Gray)
xx[y][x] = complex(float64(gray.Y), 0)
zz[y*b.Max.X+x] = gray.Y
set.Set(x, y, pixel)
}
}
y := fft.FFT2(xx)
entropy := Entropy(y)
fmt.Println("original", imag(entropy)/real(entropy), entropy, cmplx.Abs(entropy), cmplx.Phase(entropy))
rnd.Shuffle(len(zz), func(i, j int) {
zz[i], zz[j] = zz[j], zz[i]
})
for y := 0; y < b.Max.Y; y++ {
for x := 0; x < b.Max.X; x++ {
xx[y][x] = complex(float64(zz[y*b.Max.X+x]), 0)
}
}
y = fft.FFT2(xx)
entropy = Entropy(y)
fmt.Println("shuffled", imag(entropy)/real(entropy), entropy, cmplx.Abs(entropy), cmplx.Phase(entropy))
sort.Slice(zz, func(i, j int) bool {
return zz[i] < zz[j]
})
for y := 0; y < b.Max.Y; y++ {
for x := 0; x < b.Max.X; x++ {
xx[y][x] = complex(float64(zz[y*b.Max.X+x]), 0)
}
}
y = fft.FFT2(xx)
entropy = Entropy(y)
fmt.Println("sorted", imag(entropy)/real(entropy), entropy, cmplx.Abs(entropy), cmplx.Phase(entropy))
output, err := os.Create(fmt.Sprintf("gray/%s.png", name))
if err != nil {
panic(err)
}
defer output.Close()
png.Encode(output, set)
}