-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
90 lines (84 loc) · 2.02 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
package main
// Files required to build supporting package raster are found in:
// * Bitmap
// * Grayscale image
// * Read a PPM file
// * Write a PPM file
import (
"fmt"
"github.com/ArchieT/raster"
)
var g0, g1 *raster.Grmap
var ko [][]int
var kc []uint16
var mid int
func init() {
// hard code box of 9 pixels
ko = [][]int{
{-1, -1}, {0, -1}, {1, -1},
{-1, 0}, {0, 0}, {1, 0},
{-1, 1}, {0, 1}, {1, 1}}
kc = make([]uint16, len(ko))
mid = len(ko) / 2
}
func main() {
// Example file used here is Lenna50.jpg from the task "Percentage
// difference between images" converted with with the command
// convert Lenna50.jpg -colorspace gray Lenna50.ppm
// It shows very obvious compression artifacts when viewed at higher
// zoom factors.
b, err := raster.ReadPpmFile("Lenna50.ppm")
if err != nil {
fmt.Println(err)
return
}
g0 = b.Grmap()
w, h := g0.Extent()
g1 = raster.NewGrmap(w, h)
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
g1.SetPx(x, y, median(x, y))
}
}
// side by side comparison with input file shows compression artifacts
// greatly smoothed over, although at some loss of contrast.
err = g1.Bitmap().WritePpmFile("median.ppm")
if err != nil {
fmt.Println(err)
}
}
func median(x, y int) uint16 {
var n int
// construct sorted list as pixels are read. insertion sort can't be
// beat for a small number of items, plus there would be lots of overhead
// just to get numbers in and out of a library sort routine.
for _, o := range ko {
// read a pixel of the kernel
c, ok := g0.GetPx(x+o[0], y+o[1])
if !ok {
continue
}
// insert it in sorted order
var i int
for ; i < n; i++ {
if c < kc[i] {
for j := n; j > i; j-- {
kc[j] = kc[j-1]
}
break
}
}
kc[i] = c
n++
}
// compute median from sorted list
switch {
case n == len(kc): // the usual case, pixel with complete neighborhood
return kc[mid]
case n%2 == 1: // edge case, odd number of pixels
return kc[n/2]
}
// else edge case, even number of pixels
m := n / 2
return (kc[m-1] + kc[m]) / 2
}