-
Notifications
You must be signed in to change notification settings - Fork 0
/
template_finder.py
180 lines (166 loc) · 6.57 KB
/
template_finder.py
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Author: cirq
# Created Time: 2017-07-29 10:54:38
import cv2
import pickle
import numpy as np
from timer import timer
from image import Image
from template import Template
# This solution is abort for performance reason
#
# class TemplateFinder(Image, Template):
# def __init__(self, filepath, ttype):
# super(TemplateFinder, self).__init__(filepath)
# super(Image, self).__init__(ttype)
#
# if __name__ == '__main__':
# tf = TemplateFinder('images/pool.png', 'X')
# print tf.covers_hue(90)
class TemplateFinder(Image):
type_list = ['i', 'V', 'T', 'L', 'I', 'Y', 'X']
def __init__(self, filepath):
super(TemplateFinder, self).__init__(filepath)
self.__templates = {}
self.__best_template = None
@property
def templates(self):
return self.__templates
@property
def best_template(self):
return self.__best_template
def __potential(self, template):
"""
Calculate the potential function defined in Eq.(1)
:param template: A (maybe) harmonic template.
:type template: Template
:return: value of potential function.
:rtype: float
"""
hist = cv2.calcHist([self.huechannel], [0], None, [360], [0, 360])
numerator, denominator = np.float32(0), np.float32(0)
one = np.float32(1)
for i in range(360):
if template.covers_hue(i):
numerator += hist[i][0]
denominator += one
potential = numerator / denominator
return potential
def __find_one_template_linear(self, ttype):
"""
Find most suitable rotate angle, i.e., Eq.(3).
Implemented by linear searching stretegy.
:param ttype: the model type.
:type ttype: char
:return: The most suitable template instance with corresponding
potential will be recorded in the dictionary.
:rtype: None
"""
t = Template(ttype)
max_potential, max_theta = np.float32(-1), -1
for theta in range(0, 360):
t.theta = theta
tmp_potential = self.__potential(t)
if tmp_potential > max_potential:
max_potential, max_theta = tmp_potential, theta
t.theta = max_theta
self.__templates[ttype] = (t, max_potential)
def __find_one_template_binary_failed(self, ttype):
"""
To find most suitable rotate angle, i.e. Eq.(3),
attemp to implement by binary searching. But it
failed since the distribution of potentials are not
rotatedly sorted. If the model has one sector, then
it is, otherwise, the distribution is symmetric with
some pivot and will have two similar componnets.
"""
t = Template(ttype)
for theta in range(0, 360):
t.theta = theta
potential = self.__potential(t)
print theta, potential
def __find_better_template(self, p, q, beta):
"""
To judge whether template p is better or q. Eq.(4)
:param p, q: type name of a template.
:type p, q: char
:param beta: parameter $\beta'$
:type beta: float
:return: a partial ordering
:rtype: (better_template(char), worse_template(char))
"""
template_p, template_q = self.__templates[p][0], self.__templates[q][0]
potential_p, potential_q = self.__templates[p][1], self.__templates[q][1]
area_p, area_q = 0, 0
if template_p.snumber == 1:
area_p = template_p.end[0] - template_p.start[0]
elif template_p.snumber == 2:
area_p = (template_p.end[0] - template_p.start[0]) + (template_p.end[1] - template_p.start[1])
if template_q.snumber == 1:
area_q = template_q.end[0] - template_q.start[0]
elif template_q.snumber == 2:
area_q = (template_q.end[0] - template_q.start[0]) + (template_q.end[1] - template_q.start[1])
if area_p < area_q:
p, q = q, p
potential_p, potential_q = potential_q, potential_p
area_p, area_q = area_q, area_p
alpha = float(area_p) / float(area_q)
gamma = alpha / (1 + beta * (alpha - 1))
cpq = gamma * potential_p / potential_q
if cpq > 1.0:
return p, q
else:
return q, p
def find_seven_templates(self):
"""
Search for seven templates, along with potential values.
"""
print '###################################'
print '### Start Finding Templates ###'
print '###################################'
for i, ttype in enumerate(self.type_list, start=1):
self.__find_one_template_linear(ttype)
print '%7s Found one template. %-7s' % ('>'*(8-i), '<'*i)
print '###################################'
print '### Seven Templates are Found ###'
print '###################################'
def find_best_template(self, beta):
"""
To find a best template in 7.
:param beta: parameter $\beta'$
:type beta: float
"""
wins = {t:0 for t in self.type_list}
for index_p in range(6):
for index_q in range(index_p+1, 7):
p, q = self.type_list[index_p], self.type_list[index_q]
partial_order = self.__find_better_template(p, q, beta)
wins[partial_order[0]] += 1
competition = sorted(wins.items(), key=lambda t: -t[1])
self.__best_template = self.__templates[competition[0][0]][0]
print '###################################'
print '# Most harmonic Template is Found #'
print '###################################'
@timer(unit='ms')
def find_templates_with_dump(self, beta):
"""
An all-in-one method that integrate the procedure needed
for finding templates (harmonic and best harmonic), then
dumps the current object into a pickle file.
:param beta: the same as method self.find_best_template.
:type beta: float
:return: the object will be saved with pickle.
:rtype: None
"""
self.find_seven_templates()
print '\n'
self.find_best_template(beta)
print '\n'
filename = self.filename.replace('.', '@') + '.pickle'
with open(filename, 'w') as w:
pickle.dump(self, w)
print 'Object dumped successfully!'
if __name__ == '__main__':
tf = TemplateFinder('images/tulips.png')
tf.find_templates_with_dump(0.1)