cuckoo search, latin hypercube sampling
[imago.git] / intrsc.py
1 """Imago intersections module"""
2
3 from math import cos, tan, pi
4 from operator import itemgetter
5
6 import ImageDraw
7
8 def dst(line):
9     """Return normalized line."""
10     if line[0] < pi / 2:
11         line = line[0] + pi, - line[1]
12     return line
13
14 def dst_sort(lines):
15     """Return lines sorted by distance."""
16     l_max = max(l[0] for l in lines)
17     l_min = min(l[0] for l in lines)
18     if l_max - l_min > (3. / 4) * pi:
19         lines = [dst(l) for l in lines]
20     lines.sort(key=itemgetter(1))
21     return lines
22
23 def board(image, lines, show_all, do_something):
24     """Compute intersections, find stone colors and return board situation."""
25     lines = [dst_sort(l) for l in lines]
26     intersections = intersections_from_angl_dist(lines, image.size)
27
28     if show_all:
29         image_g = image.copy()
30         draw = ImageDraw.Draw(image_g)
31         for line in intersections:
32             for (x, y) in line:
33                 draw.point((x , y), fill=(120, 255, 120))
34         do_something(image_g, "intersections")
35
36     board_r = []
37     
38     for line in intersections:
39         board_r.append([stone_color(image, intersection) for intersection in
40                       line])
41     return board_r
42
43 def intersections_from_angl_dist(lines, size, get_all=True):
44     """Take grid-lines and size of the image. Return intersections."""
45     intersections = []
46     for (angl1, dist1) in lines[1]:
47         line = []
48         for (angl2, dist2) in lines[0]:
49             if abs(angl1 - angl2) > 0.4:
50                 i_x =  (- ((dist2 / cos(angl2)) - (dist1 / cos(angl1))) 
51                         / (tan(angl1) - tan(angl2)))
52                 i_y = (tan(angl1) * i_x) - (dist1 / cos(angl1))
53                 if get_all or (-size[0] / 2 < i_x < size[0] / 2 and 
54                     -size[1] / 2 < i_y < size[1] / 2):
55                     line.append((int(i_x + size[0] / 2),
56                                  int(i_y + size[1] / 2)))
57         intersections.append(line)
58     return intersections
59    
60 def stone_color(image, (x, y)):
61     """Given image and coordinates, return stone color."""
62     suma = 0.
63     for i in range(-2, 3):
64         for j in range(-2, 3):
65             try:
66                 suma += sum(image.getpixel((x + i, y + j)))
67             except IndexError:
68                 pass
69     suma /= 3 * 25
70     if suma < 55:
71         return 'B'
72     elif suma < 200: 
73         return '.'
74     else:
75         return 'W'