-
Notifications
You must be signed in to change notification settings - Fork 12
/
solver.py
executable file
·359 lines (279 loc) · 11.1 KB
/
solver.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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
#!/usr/local/bin/python
#
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import os
import cv2
import numpy as np
import logging
import argparse
import traceback
import collections
import itertools
import cPickle as pickle
import operator
import copy
import glob
import time
from enum import Enum
import image_source
import board
import pieces
import solutions
MAX_PLANES = 6
Options = None
Rect = collections.namedtuple("Rect", ["x", "y", "w", "h"])
Constraint = Enum("Constraint", "VERTICAL HORIZONTAL")
def WaitKey(delay_ms=5):
key = cv2.waitKey(delay_ms) & 0xFF
if key == 27:
raise Exception("Abort")
return chr(key)
def DebugShow(image):
global Options
if Options.verbose:
stack = sys._getframe(1)
cv2.imshow("{0}:{1}".format(stack.f_code.co_name, stack.f_lineno), image)
def Crop(img, rect):
return img[rect.y:rect.y + rect.h, rect.x:rect.x + rect.w]
def PrepareImage(image):
"""Converts color image to black and white"""
# work on gray scale
bw = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# remove noise, preserve edges
bw = cv2.bilateralFilter(bw, 9, 75, 75)
# binary threshold
bw = cv2.adaptiveThreshold(bw, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY, 11, 2)
return bw
def FindExternalContour(image_bw):
"""Returns the largest external contour."""
# all external contours
_, contours, _ = cv2.findContours(image_bw.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
logging.debug("found {} external contours in image".format(len(contours)))
# max contour by area size
largest = max(contours, key=lambda cnt: cv2.contourArea(cnt))
return Rect(*cv2.boundingRect(largest))
def FindInternalBox(bw):
"""Finds where the puzzle card is located.
Detects all vertical and horizontal lines, and returns the largest
contour that bounds them"""
# Invert colors. HoughLines searches white lines on black background
target = 255 - bw.copy()
DebugShow(target)
lines = cv2.HoughLinesP(target, 1, np.pi / 180, 100, 100, 10)
if lines is None:
logging.debug("HoughLinesP failed")
return None
logging.debug("Found {} lines using HoughLinesP".format(len(lines)))
lines_image = np.zeros_like(target)
for line in lines:
for x1, y1, x2, y2 in line:
if abs(x1 - x2) < 20:
# vertical line
x = min(x1, x2)
cv2.line(lines_image, (x, y1), (x, y2), 255, 0)
if abs(y1 - y2) < 20:
y = min(y1, y2)
cv2.line(lines_image, (x1, y), (x2, y), 255, 0)
kernel = np.ones((5, 5), np.uint8)
lines_image = cv2.dilate(lines_image, kernel, iterations=2)
DebugShow(lines_image)
return FindExternalContour(lines_image)
def FindBoard(frame_bw):
outer = FindExternalContour(frame_bw)
logging.debug("Found game's outer box {0}".format(outer))
outer_img = Crop(frame_bw, outer)
inner = FindInternalBox(outer_img)
if not inner or inner.w < 100 or inner.h < 100:
logging.debug("Cound not find game's inner box")
return None
box = Rect(outer.x + inner.x, outer.y + inner.y, inner.w, inner.h)
logging.debug("Found board location in frame {0}".format(box))
return box
def ReadCells(frame, box):
"""Reads grid images from frame. Each sub image corresponds to a single cell."""
cells = np.array([None] * 16, dtype='O').reshape(4, 4)
cell_size = np.array([box.w / 4, box.h / 4])
top_left_loc = np.array([box.x, box.y])
for selected_cell in itertools.product(range(4), range(4)):
loc = top_left_loc + np.array(selected_cell[::-1]) * cell_size
cells[selected_cell] = Crop(frame, Rect(loc[0], loc[1], cell_size[0],
cell_size[1]))
return cells
def LoadTemplates():
def ReadTemplates(base, value):
filenames = os.path.join("templates",
"{0}_{1}*.png".format(base, value.name.lower()))
logging.debug("Reading templates: {0}".format(glob.glob(filenames)))
templates = [cv2.imread(f) for f in glob.glob(filenames)]
templates = [cv2.cvtColor(t, cv2.COLOR_RGB2GRAY) for t in templates]
return templates
return dict([(o, ReadTemplates("obj", o))
for o in [board.SquareType.UP, board.SquareType.RIGHT,
board.SquareType.DOWN, board.SquareType.LEFT,
board.SquareType.ANY]] + [(c, ReadTemplates("con", c))
for c in Constraint])
def MatchTemplate(template, target):
"""Returns match score for given template"""
res = cv2.matchTemplate(target, template, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
return max_val
def DetectObjects(templates, cells):
objects = np.array([None] * 16, dtype='O').reshape(4, 4)
for selected in itertools.product(range(4), range(4)):
target = cells[selected].copy()
DebugShow(target)
matches = [(o, MatchTemplate(t, target))
for o in [board.SquareType.UP, board.SquareType.RIGHT,
board.SquareType.DOWN, board.SquareType.LEFT,
board.SquareType.ANY] for t in templates[o]]
best = max(matches, key=operator.itemgetter(1))
if best[1] < 0.6:
continue
logging.debug("Detected {0} with score {1} at {2}".format(best[0], best[1],
selected))
objects[selected] = best[0]
return objects
def DetectConstraints(templates, cells):
constraints = np.array([None] * 16, dtype='O').reshape(4, 4)
for selected in itertools.product(range(4), range(4)):
target = cells[selected].copy()
DebugShow(target)
matches = [(o, MatchTemplate(t, target))
for o in Constraint for t in templates[o]]
best = max(matches, key=operator.itemgetter(1))
if best[1] < 0.6:
continue
logging.debug("Detected {0} with score {1} at {2}".format(best[0], best[1],
selected))
constraints[selected] = best[0]
return constraints
def PassConstraints(constraints, solution):
b = solutions.PlacePieces(solution)
for selected in itertools.product(range(4), range(4)):
loc = np.array([1, 1]) + selected
if constraints[selected] is Constraint.VERTICAL:
if b[zip(loc)] not in [board.SquareType.UP, board.SquareType.DOWN,
board.SquareType.AIR]:
return False
if constraints[selected] is Constraint.HORIZONTAL:
if b[zip(loc)] not in [board.SquareType.LEFT, board.SquareType.RIGHT,
board.SquareType.AIR]:
return False
return True
def BuildPuzzleBoardFromObjects(objects):
"""Build 6x6 board and fills in the objects"""
b = board.Empty()
for selected in itertools.product(range(4), range(4)):
loc = np.array([1, 1]) + selected
if objects[selected]:
b[zip(loc)] = objects[selected]
return b
def LoadImages():
def LoadImage(orientation):
filename = os.path.join("images", orientation.name.lower() + ".png")
image = cv2.imread(filename)
return image
return dict([(o, LoadImage(o))
for o in [board.SquareType.UP, board.SquareType.RIGHT,
board.SquareType.DOWN, board.SquareType.LEFT]])
def ShowSolution(images, puzzle, solution, frame, box):
cell_size = np.array([box.w / 4, box.h / 4])
for piece_type, piece, i, j in solution:
top_left_loc = np.array([box.x, box.y]) + (np.array([j, i]) -
np.array([1, 1])) * cell_size
color = pieces.Colors[piece_type]
piece_img = np.zeros_like(frame)
for square in itertools.product(range(2), range(2)):
if piece[square] == board.SquareType.AIR:
continue
loc = top_left_loc + np.array(square[::-1]) * cell_size
piece_img = cv2.rectangle(piece_img, tuple(loc), tuple(loc + cell_size),
color, -2)
if piece[square] in images:
image = cv2.resize(images[piece[square]], tuple(cell_size))
blend = np.zeros_like(piece_img)
blend[loc[1]:loc[1] + cell_size[1], loc[0]:loc[0] + cell_size[
0]] = image
piece_img = cv2.addWeighted(piece_img, 1.0, blend, 1.0, 0)
piece_gray = cv2.cvtColor(piece_img, cv2.COLOR_RGB2GRAY)
_, piece_gray = cv2.threshold(piece_gray, 10, 255, cv2.THRESH_BINARY)
_, contours, _ = cv2.findContours(piece_gray, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
piece_img = cv2.drawContours(piece_img, contours, -1, (255, 255, 255), 3)
frame = cv2.addWeighted(frame, 1.0, piece_img, 0.7, 0)
cv2.imshow("Planes", frame)
def main():
try:
logging.basicConfig(level=logging.INFO)
parser = argparse.ArgumentParser()
parser.add_argument("--image",
type=str,
help="Process input image. Using video camera insead")
parser.add_argument("-v",
"--verbose",
action="store_true",
help="Enable debug prints")
global Options
Options = parser.parse_args()
if Options.verbose:
logging.getLogger('').handlers = []
logging.basicConfig(level=logging.DEBUG)
try:
loader = solutions.AsyncLoader()
loader.start()
if Options.image:
source = image_source.FileSource(Options.image)
else:
source = image_source.CameraSource()
templates = LoadTemplates()
images = LoadImages()
while True:
frame = source.NextFrame()
cv2.imshow("Planes", frame)
frame_bw = PrepareImage(frame)
box = FindBoard(frame_bw)
if not box:
WaitKey(5)
continue
cells = ReadCells(frame_bw, box)
objects = DetectObjects(templates, cells)
constraints = DetectConstraints(templates, cells)
puzzle = BuildPuzzleBoardFromObjects(objects)
if Options.verbose:
board.Print(puzzle)
loader.join()
matches = loader.db["board_to_solution"][hash(str(puzzle))]
if not matches:
WaitKey(5)
logging.debug("Puzzle not found in solutions DB")
continue
logging.debug("Found {0} solutions in DB".format(len(matches)))
matches = [m for m in matches if PassConstraints(constraints, m)]
logging.debug("Found {0} solutions within constraints".format(len(
matches)))
for m in matches:
ShowSolution(images, puzzle, m, frame, box)
WaitKey(0)
finally:
logging.debug("Destroying windows")
cv2.destroyAllWindows()
except Exception, e:
logging.error(traceback.format_exc())
return e
if __name__ == "__main__":
sys.exit(main())