bugs in manual mode fixed
[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 linef
19 import manual
20
21 def main():
22     """Main function of the program."""
23     
24     parser = argparse.ArgumentParser(description=__doc__)
25     parser.add_argument('file', metavar='file', nargs=1,
26                         help="image to analyse")
27     parser.add_argument('-w', type=int, default=640,
28                         help="scale image to the specified width before analysis")
29     parser.add_argument('-m', '--manual', dest='manual_mode', action='store_true',
30                         help="manual grid selection")
31     parser.add_argument('-d', '--debug', dest='show_all', action='store_true',
32                         help="show every step of the computation")
33     parser.add_argument('-s', '--save', dest='saving', action='store_true',
34                         help="save images instead of displaying them")
35     parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
36                         help="report progress")
37     args = parser.parse_args()
38
39     show_all = args.show_all
40     verbose = args.verbose
41
42     try:
43         image = Image.open(args.file[0])
44     except IOError, msg:
45         print >> sys.stderr, msg
46         return 1
47     if image.mode == 'P':
48         image = image.convert('RGB')
49     
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     do_something = im_debug.show
54     if args.saving:
55         do_something = imsave("saved/" + args.file[0][:-4] + "_" +
56                                str(image.size[0]) + "/").save
57
58     if args.manual_mode:
59         try:
60             lines = manual.find_lines(image)
61         except manual.UserQuitError:
62             #TODO ask user to try again
63             return 1
64     else:
65         lines = linef.find_lines(image, show_all, do_something, verbose)
66
67     image_g = image.copy()
68     draw = ImageDraw.Draw(image_g)
69     for line in [l for s in lines for l in s]:
70         draw.line(linef.line_from_angl_dist(line, image.size), fill=(120, 255, 120))
71     if show_all:
72         do_something(image_g, "the grid")
73  
74     intersections = intersections_from_angl_dist(lines, image.size)
75     image_g = image.copy()
76     draw = ImageDraw.Draw(image_g)
77     for line in intersections:
78         for (x, y) in line:
79             draw.point((x , y), fill=(120, 255, 120))
80     
81     for line in intersections:
82         print ' '.join([stone_color(image, intersection) for intersection in
83                        line])
84
85     if show_all:
86         do_something(image_g, "intersections")
87
88     return 0
89
90 def stone_color(image, (x, y)):
91     suma = 0.
92     for i in range(-2, 3):
93         for j in range(-2, 3):
94             try:
95                 suma += sum(image.getpixel((x + i, y + j)))
96             except IndexError:
97                 pass
98     suma /= 3 * 25
99     if suma < 55:
100         return 'B'
101     elif suma < 200: 
102         return '.'
103     else:
104         return 'W'
105
106 class imsave():
107     def __init__(self, saving_dir):
108         self.saving_dir = saving_dir
109         self.saving_num = 0
110
111     def save(self, image, title=''):
112         filename = self.saving_dir + "{0:0>2}".format(self.saving_num) + '.jpg'
113         if not os.path.isdir(self.saving_dir):
114             os.makedirs(self.saving_dir)
115         image.save(filename, 'JPEG')
116         self.saving_num += 1
117
118 def combine(image1, image2):
119     im_l1 = image1.load()
120     im_l2 = image2.load()
121
122     on_both = []
123
124     for x in xrange(image1.size[0]):
125         for y in xrange(image1.size[1]):
126             if im_l1[x, y] and im_l2[x, y]:
127                 on_both.append((x, y))
128     return on_both
129
130 def intersections_from_angl_dist(lines, size):
131     intersections = []
132     for (angl1, dist1) in sorted(lines[1], key=itemgetter(1)):
133         line = []
134         for (angl2, dist2) in sorted(lines[0], key=itemgetter(1)):
135             if abs(angl1 - angl2) > 0.4:
136                 x =  - ((dist2 / math.cos(angl2))-(dist1 / math.cos(angl1))) / (math.tan(angl1) - math.tan(angl2))
137                 y = (math.tan(angl1) * x) - (dist1 / math.cos(angl1))
138                 if (-size[0] / 2 < x < size[0] / 2 and 
139                     -size[1] / 2 < y < size[1] / 2):
140                     line.append((int(x + size[0] / 2), int(y + size[1] / 2)))
141         intersections.append(line)
142     return intersections
143
144 if __name__ == '__main__':
145     try:
146         sys.exit(main())
147     except KeyboardInterrupt:
148         print "Interrupted."
149         sys.exit()