better edge detection
[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.components2(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_hough might be used instead im_h2, but at the moment it brings a lot of
105     # noise to the second transform, which later confuses the center-finding
106     # mechanism (which is not very robust yet)
107     im_hough2 = hough2.transform(im_h2)
108     if show_all:
109         do_something(im_hough2, "second hough transform")
110
111     im_h3 = filters.high_pass(im_hough2, 120)
112     if show_all:
113         do_something(im_h3, "third high pass filter")
114      
115     im_h3 = filters.components(im_h3)
116     if show_all:
117         do_something(im_h3, "half centers")
118
119     if verbose:
120         print >> sys.stderr, "finding the grid"
121
122     lines_m = hough2.all_lines_h(im_h3)
123     lines = []
124     im_c = im_h2.convert('RGB').convert('RGB', (1, 0.5, 0.5, 0))
125     draw_c = ImageDraw.Draw(im_c)
126
127     for line_l in lines_m:
128         im_line = Image.new('L', im_h2.size)
129         draw = ImageDraw.Draw(im_line)
130         line_points = set()
131         for line in line_l:
132             draw.line(line_from_angl_dist(line, im_h2.size), fill=255, width=7)
133             draw_c.line(line_from_angl_dist(line, im_c.size), fill=(70, 70, 70), width=7)
134             for p in combine(im_h2, im_line):
135                 line_points.add(p)
136         for point in line_points:
137             draw_c.point(point, fill=(120, 255, 120))
138         lines.append(hough1.lines_from_list(line_points))
139
140     if show_all:
141         do_something(im_c, "hough x lines")
142
143     image_g = image.copy()
144     draw = ImageDraw.Draw(image_g)
145     for line in [l for s in lines for l in s]:
146         draw.line(line_from_angl_dist(line, image.size), fill=(120, 255, 120))
147     if show_all:
148         do_something(image_g, "the grid")
149
150     intersections = intersections_from_angl_dist(lines, image.size)
151     image_g = image.copy()
152     draw = ImageDraw.Draw(image_g)
153     for line in intersections:
154         for (x, y) in line:
155             draw.point((x , y), fill=(120, 255, 120))
156     
157     for line in intersections:
158         print ' '.join([stone_color(image, intersection) for intersection in
159                        line])
160
161     if show_all:
162         do_something(image_g, "intersections")
163
164     return 0
165
166 def stone_color(image, (x, y)):
167     suma = 0.
168     for i in range(-2, 3):
169         for j in range(-2, 3):
170             try:
171                 suma += sum(image.getpixel((x + i, y + j)))
172             except IndexError:
173                 pass
174     suma /= 3 * 25
175     if suma < 55:
176         return 'B'
177     elif suma < 200: 
178         return '.'
179     else:
180         return 'W'
181
182 def image_save(image, title=''):
183     global Saving_dir
184     global Saving_num
185     filename = Saving_dir + "{0:0>2}".format(Saving_num) + '.jpg'
186     if not os.path.isdir(Saving_dir):
187         os.makedirs(Saving_dir)
188     image.save(filename, 'JPEG')
189     Saving_num += 1
190
191 def combine(image1, image2):
192     im_l1 = image1.load()
193     im_l2 = image2.load()
194
195     on_both = []
196
197     for x in xrange(image1.size[0]):
198         for y in xrange(image1.size[1]):
199             if im_l1[x, y] and im_l2[x, y]:
200                 on_both.append((x, y))
201     return on_both
202
203 def line_from_angl_dist((angle, distance), size):
204     x1 = - size[0] / 2
205     y1 = int(round((x1 * math.sin(angle) - distance) / math.cos(angle))) + size[1] / 2
206     x2 = size[0] / 2 
207     y2 = int(round((x2 * math.sin(angle) - distance) / math.cos(angle))) + size[1] / 2
208     return [(0, y1), (size[0] - 1, y2)]
209
210 def intersections_from_angl_dist(lines, size):
211     intersections = []
212     for (angl1, dist1) in sorted(lines[1], key=itemgetter(1)):
213         line = []
214         for (angl2, dist2) in sorted(lines[0], key=itemgetter(1)):
215             if abs(angl1 - angl2) > 0.4:
216                 x =  - ((dist2 / math.cos(angl2))-(dist1 / math.cos(angl1))) / (math.tan(angl1) - math.tan(angl2))
217                 y = (math.tan(angl1) * x) - (dist1 / math.cos(angl1))
218                 if (-size[0] / 2 < x < size[0] / 2 and 
219                     -size[1] / 2 < y < size[1] / 2):
220                     line.append((int(x + size[0] / 2), int(y + size[1] / 2)))
221         intersections.append(line)
222     return intersections
223
224 if __name__ == '__main__':
225     sys.exit(main())