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