Created
October 6, 2010 02:06
-
-
Save wolever/612687 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
diff --git a/show.html b/show.html | |
new file mode 100644 | |
--- /dev/null | |
+++ b/show.html | |
@@ -0,0 +1,9 @@ | |
+<img id="theImg" src="/tmp/x.png" /> | |
+<script> | |
+var theImg = document.getElementById("theImg"); | |
+function refreshImg() { | |
+ theImg.src = "file:///tmp/x.png?rand=" + (new Date()).getTime(); | |
+ setTimeout(refreshImg, 100); | |
+} | |
+refreshImg(); | |
+</script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
diff --git a/cv_processimage.py b/cv_processimage.py | |
--- a/cv_processimage.py | |
+++ b/cv_processimage.py | |
@@ -8,6 +8,8 @@ | |
import cv | |
import numpy as np | |
+from set import find_set, valid_cards, card_is_valid | |
+ | |
def distance(p0, p1): | |
""" Returns the distance absolute between p0 and p1. | |
>>> distance((0, 0), (0, -1)) | |
@@ -259,11 +261,11 @@ | |
difference = np.sum(np.abs(border_mean - shape_mean)) | |
- blank_threshold = sum(np.std(border, axis=0)) | |
- striped_threshold = 3 * blank_threshold | |
+ empty_threshold = sum(np.std(border, axis=0)) | |
+ striped_threshold = 3 * empty_threshold | |
- if difference < blank_threshold: | |
- return "blank" | |
+ if difference < empty_threshold: | |
+ return "empty" | |
if difference < striped_threshold: | |
return "striped" | |
return "solid" | |
@@ -298,20 +300,11 @@ | |
lines = [ theta for rho, theta in lines_iter][:4] | |
- """ | |
- color = cv.CreateImage((edges.width, edges.height), 8, 3) | |
- cv.CvtColor(edges, color, cv.CV_GRAY2RGB) | |
- for line in lines: | |
- cv.Line(color, line[0], line[1], cv.CV_RGB(255, 0, 0), 2, 8) | |
- show(color) | |
- return "unknown" | |
- """ | |
- | |
if not lines: | |
return "unknown (no lines)" | |
- line_strs = [ "%0.02f" %(line, ) for line in lines ] | |
- print "lines:", ", ".join(line_strs) | |
+ #line_strs = [ "%0.02f" %(line, ) for line in lines ] | |
+ #print "lines:", ", ".join(line_strs) | |
if all(0 <= line < 0.1 or 3.00 < line < 3.15 for line in lines): | |
return "oval" | |
@@ -322,31 +315,28 @@ | |
return "wiggle" | |
def cards_in_image(img): | |
- return [ extract_card(img, rect) for rect in find_rects(img) ] | |
+ return [ (rect, extract_card(img, rect)) for rect in find_rects(img) ] | |
# interactive/dev functions | |
def extract_all_cards(): | |
for set in (0, 1, 2, 3, 4, 5): | |
img = cv.LoadImage("images/set%d.png" %(set, )) | |
- for num, card in enumerate(cards_in_image(img)): | |
+ for num, (_, card) in enumerate(cards_in_image(img)): | |
cv.SaveImage("images/card%d_%d.png" %(set, num), card) | |
-def draw_rects(color_img, rects): | |
+def draw_rects(color_img, rects, color): | |
""" | |
rects is py list containing 4-pt numpy arrays. Step through the list | |
and draw a polygon for each 4-group | |
""" | |
- RED = (0, 0, 255) | |
- GREEN = (0, 255, 0) | |
- color, othercolor = RED, GREEN | |
for rect in rects: | |
cv.PolyLine(color_img, [rect], True, color, 3, cv.CV_AA, 0) | |
- color, othercolor = othercolor, color | |
def test_find_cards(): | |
global show | |
old_show = show | |
+ show = lambda *args: None | |
errs = False | |
expected = { | |
"set1.png": 9, | |
@@ -359,7 +349,6 @@ | |
for file, expected in expected.items(): | |
file = "images/" + file | |
- show = lambda *args: None | |
print "testing %s..." %(file, ), | |
color_img = cv.LoadImage(file) | |
rects = find_rects(color_img) | |
@@ -368,12 +357,15 @@ | |
print "ok." | |
continue | |
print "error: expected %d cards, got %d" %(expected, len(rects)) | |
- show = old_show | |
- draw_rects(color_img, rects) | |
- show(color_img) | |
+ draw_rects(color_img, rects, (0xFF, 0, 0)) | |
+ old_show(color_img) | |
errs = True | |
return errs | |
+def test_identify_card(): | |
+ global show | |
+ | |
+ | |
def main(): | |
import doctest | |
""" | |
@@ -383,12 +375,24 @@ | |
return | |
""" | |
- img = cv.LoadImage("images/set4.png") | |
+ img = cv.LoadImage("images/set2.png") | |
cards = cards_in_image(img) | |
- for card in cards: | |
- print identify_card(card) | |
- show(card) | |
- raw_input() | |
+ cards = [ (rect, identify_card(card)) for (rect, card) in cards ] | |
+ print "found cards:" | |
+ for rect, card in cards: | |
+ print card, "(invalid)" if not card_is_valid(card) else "" | |
+ if not card_is_valid(card): | |
+ draw_rects(img, [ rect ], (0, 0, 0xFF)) | |
+ | |
+ | |
+ set = find_set(valid_cards(card for _, card in cards)) | |
+ if set: | |
+ cards_dict = dict((card, rect) for (rect, card) in cards) | |
+ draw_rects(img, (cards_dict[t] for t in set), (0, 0xFF, 0)) | |
+ else: | |
+ print "No sets found :(" | |
+ show(img) | |
if __name__ == "__main__": | |
main() | |
diff --git a/set.py b/set.py | |
--- a/set.py | |
+++ b/set.py | |
@@ -2,13 +2,15 @@ | |
from itertools import product, combinations, ifilter | |
from random import shuffle | |
+possible_card_values = [ | |
+ [ "one", "two", "three" ], | |
+ [ "red", "green", "purple" ], | |
+ [ "empty", "striped", "solid" ], | |
+ [ "wiggle", "diamond", "oval" ], | |
+] | |
+ | |
def make_deck(): | |
- deck = list(product( | |
- [ "one", "two", "three" ], | |
- [ "red", "green", "purple" ], | |
- [ "empty", "striped", "solid" ], | |
- [ "wiggle", "diamond", "oval" ], | |
- )) | |
+ deck = list(product(possible_card_values)) | |
shuffle(deck) | |
return deck | |
@@ -33,6 +35,13 @@ | |
valid = filter(lambda x: all_equal(*x) or none_equal(*x), variables) | |
return len(valid) == len(variables) | |
+def card_is_valid(card): | |
+ return len(card) == 4 and \ | |
+ all(card[x] in possible_card_values[x] for x in range(4)) | |
+ | |
+def valid_cards(cards): | |
+ return filter(card_is_valid, cards) | |
+ | |
def find_set(board): | |
for cards in ifilter(valid_set, combinations(board, 3)): | |
return cards | |
@@ -62,5 +71,6 @@ | |
print "Done." | |
print board | |
-deck = make_deck() | |
-play_set(deck) | |
+if __name__ == "__main__": | |
+ deck = make_deck() | |
+ play_set(deck) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# Copyright (c) 2010 David Wolever <david@wolever.net> | |
# See LICENSE_MIT.txt for full terms. | |
"""usage: ifdiff IFDEF_NAME < input.diff > output.diff | |
For example: | |
$ hg diff -r original:tip | ifdiff GROUP3 > /tmp/result.diff | |
$ hg co original | |
$ patch -p1 < /tmp/result.diff""" | |
import os | |
import re | |
import sys | |
from optparse import OptionParser | |
class pushback_iter(object): | |
def __init__(self, iterable): | |
self.stack = [] | |
self.iterable = iterable | |
def pushback(self, val): | |
self.stack.append(val) | |
def next(self): | |
if self.stack: | |
return self.stack.pop() | |
return self.iterable.next() | |
def __iter__(self): | |
return self | |
def do_ifdiff(lines, output, options): | |
lines = pushback_iter(lines) | |
options.cur_result_lineno = 1 | |
for line in lines: | |
if line.startswith("@@"): | |
lines.pushback(line) | |
do_hunk(lines, output, options) | |
else: | |
output.write(line) | |
def do_hunk(lines, output, options): | |
match = re.match("^@@ -([0-9]+)", lines.next()) | |
try: | |
start_lineno = int(match.group(1)) | |
except Exception, e: | |
sys.stderr.write(("error parsing %r: %s\n" %(match.group(1), e))) | |
sys.exit(1) | |
hunk_lines = [] | |
for line in lines: | |
if line.startswith("@@") or line.startswith("diff"): | |
lines.pushback(line) | |
break | |
hunk_lines.append(line) | |
result = [] | |
last_prefix = None | |
for line in hunk_lines: | |
if last_prefix != line[:1] and last_prefix in ("+", "-"): | |
result.append("+#endif\n") | |
if line[:1] == "-": | |
if last_prefix != "-": | |
result.append("+#if !%s\n" %(options.ifdefname, )) | |
result.append(" " + line[1:]) | |
elif line[:1] == "+": | |
if last_prefix != "+": | |
result.append("+#if %s\n" %(options.ifdefname, )) | |
result.append(line) | |
else: | |
result.append(line) | |
last_prefix = line[:1] or " " | |
if last_prefix in ("+", "-"): | |
result.append("+#endif\n") | |
lines_added = len(filter(lambda line: line.startswith("+"), result)) | |
old_lines = len(result) - lines_added | |
output.write("@@ -%s,%s +%s,%s @@\n" %(start_lineno, old_lines, | |
options.cur_result_lineno, | |
len(result))) | |
for line in result: | |
output.write(line) | |
options.cur_result_lineno += lines_added | |
def main(): | |
parser = OptionParser(usage=__doc__) | |
(options, args) = parser.parse_args() | |
if len(args) != 1: | |
parser.error("must supply an IFDEF_NAME") | |
options.ifdefname = args[0] | |
lines = sys.stdin.xreadlines() | |
do_ifdiff(lines, sys.stdout, options) | |
if __name__ == "__main__": | |
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in | |
all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | |
THE SOFTWARE. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment