ea9ee6c24f62221dfe83e4c62fc429dca3ca1395
[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 Saving_dir = ''
21 Saving_num = 0
22
23 def main():
24     """Main function of the program."""
25     
26     parser = argparse.ArgumentParser(description=__doc__)
27     parser.add_argument('file', metavar='file', nargs=1,
28                         help="image to analyse")
29     parser.add_argument('-w', type=int, default=640,
30                         help="scale image to the specified width before analysis")
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='do_something', action='store_const',
34                         const=image_save, default=im_debug.show,
35                         help="save images instead of displaying them")
36     parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
37                         help="report progress")
38     args = parser.parse_args()
39
40     show_all = args.show_all
41     do_something = args.do_something
42     verbose = args.verbose
43
44     try:
45         image = Image.open(args.file[0])
46     except IOError, msg:
47         print >> sys.stderr, msg
48         return 1
49     if image.mode == 'P':
50         image = image.convert('RGB')
51     
52     if image.size[0] > args.w:
53         image = image.resize((args.w, int((float(args.w)/image.size[0]) *
54                               image.size[1])), Image.ANTIALIAS)
55     global Saving_dir
56     Saving_dir = "saved/" + args.file[0][:-4] + "_" + str(image.size[0]) + "/"
57     
58     lines = linef.find_lines(image, show_all, do_something, verbose)
59
60     intersections = intersections_from_angl_dist(lines, image.size)
61     image_g = image.copy()
62     draw = ImageDraw.Draw(image_g)
63     for line in intersections:
64         for (x, y) in line:
65             draw.point((x , y), fill=(120, 255, 120))
66     
67     for line in intersections:
68         print ' '.join([stone_color(image, intersection) for intersection in
69                        line])
70
71     if show_all:
72         do_something(image_g, "intersections")
73
74     return 0
75
76 def stone_color(image, (x, y)):
77     suma = 0.
78     for i in range(-2, 3):
79         for j in range(-2, 3):
80             try:
81                 suma += sum(image.getpixel((x + i, y + j)))
82             except IndexError:
83                 pass
84     suma /= 3 * 25
85     if suma < 55:
86         return 'B'
87     elif suma < 200: 
88         return '.'
89     else:
90         return 'W'
91
92 def image_save(image, title=''):
93     global Saving_dir
94     global Saving_num
95     filename = Saving_dir + "{0:0>2}".format(Saving_num) + '.jpg'
96     if not os.path.isdir(Saving_dir):
97         os.makedirs(Saving_dir)
98     image.save(filename, 'JPEG')
99     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()