installation instructions
[imago.git] / intrsc.py
1 from math import sin, cos, tan
2 from operator import itemgetter
3
4 import Image, ImageDraw
5
6 def board(image, lines, show_all, do_something):
7     intersections = intersections_from_angl_dist(lines, image.size)
8     image_g = image.copy()
9     draw = ImageDraw.Draw(image_g)
10     for line in intersections:
11         for (x, y) in line:
12             draw.point((x , y), fill=(120, 255, 120))
13
14     if show_all:
15         do_something(image_g, "intersections")
16
17     board = []
18     
19     for line in intersections:
20         board.append([stone_color(image, intersection) for intersection in
21                       line])
22     return board
23
24 def intersections_from_angl_dist(lines, size, get_all=False):
25     intersections = []
26     for (angl1, dist1) in sorted(lines[1], key=itemgetter(1)):
27         line = []
28         for (angl2, dist2) in sorted(lines[0], key=itemgetter(1)):
29             if abs(angl1 - angl2) > 0.4:
30                 x =  - ((dist2 / cos(angl2)) - (dist1 / cos(angl1))) / (tan(angl1) - tan(angl2))
31                 y = (tan(angl1) * x) - (dist1 / cos(angl1))
32                 if get_all or (-size[0] / 2 < x < size[0] / 2 and 
33                     -size[1] / 2 < y < size[1] / 2):
34                     line.append((int(x + size[0] / 2), int(y + size[1] / 2)))
35         intersections.append(line)
36     return intersections
37    
38 def stone_color(image, (x, y)):
39     suma = 0.
40     for i in range(-2, 3):
41         for j in range(-2, 3):
42             try:
43                 suma += sum(image.getpixel((x + i, y + j)))
44             except IndexError:
45                 pass
46     suma /= 3 * 25
47     if suma < 55:
48         return 'B'
49     elif suma < 200: 
50         return '.'
51     else:
52         return 'W'