forked from 3d0c/imagio
/
roi.go
134 lines (103 loc) · 2.5 KB
/
roi.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package query
import (
"log"
"strconv"
"strings"
)
type Rect struct {
X int
Y int
Width int
Height int
}
type Roi struct {
InitArea *Rect
calc func(x, y, w, h int) *Rect
}
var handlers = map[string]func(int, int, int, int) *Rect{
"left": func(x, y, w, h int) *Rect {
return &Rect{0, 0, w, h}
},
"right": func(x, y, w, h int) *Rect {
return &Rect{x - w, 0, w, h}
},
"bleft": func(x, y, w, h int) *Rect {
return &Rect{0, y - h, w, h}
},
"bright": func(x, y, w, h int) *Rect {
return &Rect{x - w, y - h, w, h}
},
"center": func(x, y, w, h int) *Rect {
return &Rect{(x - w) / 2, (y - h) / 2, w, h}
},
}
// ->x,y,w,h 4
// this.InitArea{x,y,w,h}
// this.calc = nil
// <- InitArea
// ->center,w,h 3
// this.InitArea{0,0,w,h}
// this.calc = handlers["center"]
// <- calculated x,y from source image (w,h are user defined)
// ->x,y 2
// this.InitArea{x,y,0,0}
// this.calc = nil
// <- InitArea (w,h are 0)
//
func (*Roi) Construct(i ...interface{}) *Roi {
var found bool
if len(i) != 1 {
log.Printf("Wrong arguments count = %d. Expecting 1\n", len(i))
return nil
}
if i[0].([]interface{})[0].(string) == "" {
return nil
}
v := i[0].([]interface{})[0].(string)
this := &Roi{calc: nil}
parts := strings.Split(v, ",")
switch len(parts) {
case 4:
x, err := strconv.Atoi(parts[0])
y, err := strconv.Atoi(parts[1])
w, err := strconv.Atoi(parts[2])
h, err := strconv.Atoi(parts[3])
this.InitArea = &Rect{x, y, w, h}
if err != nil {
log.Printf("Illegal parameters: x,y,width,height should be integers, `%s` given. Error: %v\n", v, err)
return nil
}
break
case 3:
w, err := strconv.Atoi(parts[1])
h, err := strconv.Atoi(parts[2])
if err != nil {
log.Println("Illegal parameters. width and height should be integers, `%s` given. Error: %v\n", v, err)
return nil
}
this.InitArea = &Rect{0, 0, w, h}
if this.calc, found = handlers[parts[0]]; !found {
log.Printf("Illegal roi shortcut `%s`\n", parts[0])
return nil
}
break
case 2:
x, err := strconv.Atoi(parts[0])
y, err := strconv.Atoi(parts[1])
if err != nil {
log.Printf("Illegal parameters. x,y should be integers, `%s` given. Error: %v\n", v, err)
return nil
}
this.InitArea = &Rect{x, y, 0, 0}
break
default:
return nil
}
return this
}
func (this *Roi) Calc(orig *PixelDim) *Rect {
if this.calc == nil {
return this.InitArea
}
return this.calc(orig.Width, orig.Height, this.InitArea.Width, this.InitArea.Height)
}