grid lines in debugging mode
[imago.git] / imago.py
1 #!/usr/bin/env python
2
3 """Go image recognition"""
4
5 import sys
6 import os
7 import math
8 import argparse
9 from operator import itemgetter
10
11 try:
12     import Image, ImageDraw
13 except ImportError, msg:
14     print >> sys.stderr, msg
15     sys.exit(1)
16
17 import im_debug
18 import filters
19 from hough import Hough
20
21 Saving_dir = ''
22 Saving_num = 0
23
24 def main():
25     """Main function of the program."""
26     
27     parser = argparse.ArgumentParser(description=__doc__)
28     parser.add_argument('file', metavar='file', nargs=1,
29                         help="image to analyse")
30     parser.add_argument('-w', type=int, default=640,
31                         help="scale image to the specified width before analysis")
32     parser.add_argument('-d', '--debug', dest='show_all', action='store_true',
33                         help="show every step of the computation")
34     parser.add_argument('-s', '--save', dest='do_something', action='store_const',
35                         const=image_save, default=im_debug.show,
36                         help="save images instead of displaying them")
37     parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
38                         help="report progress")
39     args = parser.parse_args()
40
41     show_all = args.show_all
42     do_something = args.do_something
43     verbose = args.verbose
44
45     try:
46         image = Image.open(args.file[0])
47     except IOError, msg:
48         print >> sys.stderr, msg
49         return 1
50     if image.mode == 'P':
51         image = image.convert('RGB')
52     
53     if image.size[0] > args.w:
54         image = image.resize((args.w, int((float(args.w)/image.size[0]) *
55                               image.size[1])), Image.ANTIALIAS)
56     global Saving_dir
57     Saving_dir = "saved/" + args.file[0][:-4] + "_" + str(image.size[0]) + "/"
58     
59     if verbose:
60         print >> sys.stderr, "preprocessing"
61
62     if show_all:
63         do_something(image, "original image")
64
65     im_l = image.convert('L')
66     if show_all:
67         do_something(im_l, "ITU-R 601-2 luma transform")
68
69     if verbose:
70         print >> sys.stderr, "edge detection"
71
72     im_edges = filters.edge_detection(im_l)
73     if show_all:    
74         do_something(im_edges, "edge detection")
75
76     im_h = filters.high_pass(im_edges, 100)
77     if show_all:
78         do_something(im_h, "high pass filters")
79     
80     if verbose:
81         print >> sys.stderr, "hough transform"
82
83     hough1 = Hough(im_h.size)
84     im_hough = hough1.transform(im_h)
85     if show_all:
86         do_something(im_hough, "hough transform")
87
88     im_hough = filters.peaks(im_hough)
89     if show_all:
90         do_something(im_hough, "peak extraction")
91                
92     im_h2 = filters.high_pass(im_hough, 120)
93     if show_all:
94         do_something(im_h2, "second high pass filters")
95
96     im_h2 = filters.components(im_h2)
97     if show_all:
98         do_something(im_h2, "components centers")
99
100     if verbose:
101         print >> sys.stderr, "second hough transform"
102
103     hough2 = Hough(im_h2.size)
104     im_hough2 = hough2.transform(im_h2)
105     if show_all:
106         do_something(im_hough2, "second hough transform")
107
108     im_h3 = filters.high_pass(im_hough2, 120)
109     if show_all:
110         do_something(im_h3, "third high pass filter")
111      
112     im_h3 = filters.half_centers(im_h3)
113     if show_all:
114         do_something(im_h3, "half centers")
115
116     if verbose:
117         print >> sys.stderr, "finding the grid"
118
119     lines_m = hough2.all_lines(im_h3)
120     lines = []
121
122     for line in lines_m:
123         im_line = Image.new('L', im_h2.size)
124         draw = ImageDraw.Draw(im_line)
125         draw.line(line_from_angl_dist(line, im_h2.size), fill=255, width=5)
126         if show_all:
127             do_something(im_line, "line")
128         im_c = combine(im_h2, im_line)
129         if show_all:
130             do_something(im_c, "hough x lines")
131         lines.append(hough1.all_lines(im_c))
132
133     image_g = image.copy()
134     draw = ImageDraw.Draw(image_g)
135     for line in [l for s in lines for l in s]:
136         draw.line(line_from_angl_dist(line, image.size), fill=(120, 255, 120))
137     if show_all:
138         do_something(image_g, "the grid")
139
140     intersections = intersections_from_angl_dist(lines, image.size)
141     image_g = image.copy()
142     draw = ImageDraw.Draw(image_g)
143     for line in intersections:
144         for (x, y) in line:
145             draw.point((x , y), fill=(120, 255, 120))
146     
147     for line in intersections:
148         print ' '.join([stone_color(image, intersection) for intersection in
149                        line])
150
151     if show_all:
152         do_something(image_g, "intersections")
153
154     return 0
155
156 def stone_color(image, (x, y)):
157     suma = 0.
158     for i in range(-2, 3):
159         for j in range(-2, 3):
160             suma += sum(image.getpixel((x + i, y + j)))
161     suma /= 3 * 25
162     if suma < 55:
163         return 'B'
164     elif suma < 200: 
165         return '.'
166     else:
167         return 'W'
168
169 def image_save(image, title=''):
170     global Saving_dir
171     global Saving_num
172     filename = Saving_dir + "{0:0>2}".format(Saving_num) + '.jpg'
173     if not os.path.isdir(Saving_dir):
174         os.makedirs(Saving_dir)
175     image.save(filename, 'JPEG')
176     Saving_num += 1
177
178 def combine(image1, image2):
179     im_l1 = image1.load()
180     im_l2 = image2.load()
181
182     im_n = Image.new('L', image1.size)
183     im_nl = im_n.load()
184
185     for x in xrange(image1.size[0]):
186         for y in xrange(image1.size[1]):
187             if im_l1[x, y] and im_l2[x, y]:
188                 im_nl[x, y] = 255
189     return im_n
190
191 def line_from_angl_dist((angle, distance), size):
192     x1 = - size[0] / 2
193     y1 = int(round((x1 * math.sin(angle) - distance) / math.cos(angle))) + size[1] / 2
194     x2 = size[0] / 2 
195     y2 = int(round((x2 * math.sin(angle) - distance) / math.cos(angle))) + size[1] / 2
196     return [(0, y1), (size[0] - 1, y2)]
197
198 def intersections_from_angl_dist(lines, size):
199     intersections = []
200     for (angl1, dist1) in sorted(lines[1], key=itemgetter(1)):
201         line = []
202         for (angl2, dist2) in lines[0]:
203             if abs(angl1 - angl2) > 0.4:
204                 x =  - ((dist2 / math.cos(angl2))-(dist1 / math.cos(angl1))) / (math.tan(angl1) - math.tan(angl2))
205                 y = (math.tan(angl1) * x) - (dist1 / math.cos(angl1))
206                 line.append((int(x + size[0] / 2), int(y + size[1] / 2)))
207         intersections.append(line)
208     return intersections
209
210 if __name__ == '__main__':
211     sys.exit(main())