61e255809002d28fa40857a5dd43690acb5aa96f
[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.size[0] > args.w:
51         image = image.resize((args.w, int((float(args.w)/image.size[0]) *
52                               image.size[1])), Image.ANTIALIAS)
53     global Saving_dir
54     Saving_dir = "saved/" + args.file[0][:-4] + "_" + str(image.size[0]) + "/"
55     
56     if verbose:
57         print >> sys.stderr, "preprocessing"
58
59     if show_all:
60         do_something(image, "original image")
61
62     im_l = image.convert('L')
63     if show_all:
64         do_something(im_l, "ITU-R 601-2 luma transform")
65
66     if verbose:
67         print >> sys.stderr, "edge detection"
68
69     im_edges = filters.edge_detection(im_l)
70     if show_all:    
71         do_something(im_edges, "edge detection")
72
73     im_h = filters.high_pass(im_edges, 100)
74     if show_all:
75         do_something(im_h, "high pass filters")
76     
77     if verbose:
78         print >> sys.stderr, "hough transform"
79
80     hough1 = Hough(im_h.size)
81     im_hough = hough1.transform(im_h)
82     if show_all:
83         do_something(im_hough, "hough transform")
84
85     im_hough = filters.peaks(im_hough)
86     if show_all:
87         do_something(im_hough, "peak extraction")
88                
89     im_h2 = filters.high_pass(im_hough, 120)
90     if show_all:
91         do_something(im_h2, "second high pass filters")
92
93     im_h2 = filters.components(im_h2)
94     if show_all:
95         do_something(im_h2, "components centers")
96
97     if verbose:
98         print >> sys.stderr, "second hough transform"
99
100     hough2 = Hough(im_h2.size)
101     im_hough2 = hough2.transform(im_h2)
102     if show_all:
103         do_something(im_hough2, "second hough transform")
104
105     im_h3 = filters.high_pass(im_hough2, 120)
106     if show_all:
107         do_something(im_h3, "third high pass filter")
108      
109     im_h3 = filters.half_centers(im_h3)
110     if show_all:
111         do_something(im_h3, "half centers")
112
113     if verbose:
114         print >> sys.stderr, "finding the grid"
115
116     lines_m = hough2.all_lines(im_h3)
117     lines = []
118
119     for line in lines_m:
120         im_line = Image.new('L', im_h2.size)
121         draw = ImageDraw.Draw(im_line)
122         draw.line(line_from_angl_dist(line, im_h2.size), fill=255, width=5)
123         if show_all:
124             do_something(im_line, "line")
125         im_c = combine(im_h2, im_line)
126         if show_all:
127             do_something(im_c, "hough x lines")
128         lines.append(hough1.all_lines(im_c))
129
130     print lines[0]
131     print lines[1]
132
133     intersections = intersections_from_angl_dist(lines, image.size)
134     image_g = image.copy()
135     draw = ImageDraw.Draw(image_g)
136     for line in intersections:
137         for (x, y) in line:
138             draw.point((x , y), fill=(120, 255, 120))
139     
140     for line in intersections:
141         print ' '.join([stone_color(image, intersection) for intersection in
142                        line])
143
144     if show_all:
145         do_something(image_g, "the grid")
146
147     return 0
148
149 def stone_color(image, (x, y)):
150     suma = 0.
151     for i in range(-2, 3):
152         for j in range(-2, 3):
153             suma += sum(image.getpixel((x + i, y + j)))
154     suma /= 3 * 25
155     if suma < 55:
156         return 'B'
157     elif suma < 200: 
158         return '.'
159     else:
160         return 'W'
161
162 def image_save(image, title=''):
163     global Saving_dir
164     global Saving_num
165     filename = Saving_dir + "{0:0>2}".format(Saving_num) + '.jpg'
166     if not os.path.isdir(Saving_dir):
167         os.makedirs(Saving_dir)
168     image.save(filename, 'JPEG')
169     Saving_num += 1
170
171 def combine(image1, image2):
172     im_l1 = image1.load()
173     im_l2 = image2.load()
174
175     im_n = Image.new('L', image1.size)
176     im_nl = im_n.load()
177
178     for x in xrange(image1.size[0]):
179         for y in xrange(image1.size[1]):
180             if im_l1[x, y] and im_l2[x, y]:
181                 im_nl[x, y] = 255
182     return im_n
183
184 def line_from_angl_dist((angle, distance), size):
185     x1 = - size[0] / 2
186     y1 = int(round((x1 * math.sin(angle) - distance) / math.cos(angle))) + size[1] / 2
187     x2 = size[0] / 2 
188     y2 = int(round((x2 * math.sin(angle) - distance) / math.cos(angle))) + size[1] / 2
189     return [(0, y1), (size[0] - 1, y2)]
190
191 def intersections_from_angl_dist(lines, size):
192     intersections = []
193     for (angl1, dist1) in sorted(lines[1], key=itemgetter(1)):
194         line = []
195         for (angl2, dist2) in lines[0]:
196             if abs(angl1 - angl2) > 0.4:
197                 x =  - ((dist2 / math.cos(angl2))-(dist1 / math.cos(angl1))) / (math.tan(angl1) - math.tan(angl2))
198                 y = (math.tan(angl1) * x) - (dist1 / math.cos(angl1))
199                 line.append((int(x + size[0] / 2), int(y + size[1] / 2)))
200         intersections.append(line)
201     return intersections
202
203 if __name__ == '__main__':
204     sys.exit(main())