511027bcb9a91050118a0201da50198c66ccac2f
[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
10 try:
11     import Image, ImageDraw
12 except ImportError, msg:
13     print >>sys.stderr, msg
14     sys.exit(1)
15
16 import im_debug
17 import filters
18 from hough import Hough
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 anlyse")
29     parser.add_argument('-w', type=int, default=640,
30                         help="scales 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     args = parser.parse_args()
37
38     show_all = args.show_all
39     do_something = args.do_something    
40
41     try:
42         image = Image.open(args.file[0])
43     except IOError, msg:
44         print >>sys.stderr, msg
45         return 1
46     if image.size[0] > args.w:
47         image = image.resize((args.w, int((float(args.w)/image.size[0]) *
48                               image.size[1])), Image.ANTIALIAS)
49     global Saving_dir
50     Saving_dir = "saved/" + args.file[0][:-4] + "_" + str(image.size[0]) + "/"
51     
52     if show_all:
53         do_something(image, "original image")
54
55     im_l = image.convert('L')
56     if show_all:
57         do_something(im_l, "ITU-R 601-2 luma transform")
58
59     im_edges = filters.edge_detection(im_l)
60     if show_all:    
61         do_something(im_edges, "edge detection")
62
63     im_h = filters.high_pass(im_edges, 100)
64     if show_all:
65         do_something(im_h, "high pass filters")
66     
67     hough1 = Hough(im_h.size)
68     im_hough = hough1.transform(im_h)
69     if show_all:
70         do_something(im_hough, "hough transform")
71
72     im_hough = filters.peaks(im_hough)
73     if show_all:
74         do_something(im_hough, "peak extraction")
75                
76     im_h2 = filters.high_pass(im_hough, 120)
77     if show_all:
78         do_something(im_h2, "second high pass filters")
79
80     im_c = filters.components(im_h2)
81     if show_all:
82         do_something(im_c, "components centers")
83
84     """
85     hough2 = Hough(im_h2.size)
86     im_hough2 = hough2.transform(im_h2)
87     if show_all:
88         do_something(im_hough2, "second hough transform")
89
90     im_h3 = filters.high_pass(im_hough2, 120)
91     if show_all:
92         do_something(im_h3, "third high pass filters")
93      
94     lines = hough2.find_angle_distance(im_h3)
95
96     im_lines = Image.new('L', im_h2.size)
97
98     draw = ImageDraw.Draw(im_lines)
99
100     for line in lines:
101         draw.line(line_from_angl_dist(line, im_h2.size), fill=255)
102     if show_all:
103         do_something(im_lines, "lines")
104
105     im_c = combine(im_h2, im_lines)
106     if show_all:
107         do_something(im_c, "first hough x lines")
108
109     collapse(im_c)
110     if show_all:
111         do_something(im_c, "optimalised hough")
112     """
113
114     lines = hough1.all_lines(im_c)
115     draw = ImageDraw.Draw(image)
116     for line in lines:
117         draw.line(line_from_angl_dist(line, image.size), fill=(120, 255, 120))
118
119     do_something(image, "the grid")
120
121     return 0
122
123 def image_save(image, title=''):
124     global Saving_dir
125     global Saving_num
126     filename = Saving_dir + "{0:0>2}".format(Saving_num) + '.jpg'
127     if not os.path.isdir(Saving_dir):
128         os.makedirs(Saving_dir)
129     image.save(filename, 'JPEG')
130     Saving_num += 1
131
132 def collapse(image):
133     #HACK
134     im_l = image.load()
135     last = False
136     for y in xrange(image.size[1]):
137         for x in xrange(image.size[0]):
138             if im_l[x, y] and last:
139                 im_l[x, y] = 0
140                 last = False
141             elif im_l[x, y]:
142                 last = True
143             elif last:
144                 last = False
145
146 def combine(image1, image2):
147     im_l1 = image1.load()
148     im_l2 = image2.load()
149
150     im_n = Image.new('L', image1.size)
151     im_nl = im_n.load()
152
153     for x in xrange(image1.size[0]):
154         for y in xrange(image1.size[1]):
155             if im_l1[x, y] and im_l2[x, y]:
156                 im_nl[x, y] = 255
157     return im_n
158
159 def line_from_angl_dist((angle, distance), size):
160     x1 = - size[0] / 2
161     y1 = int(round((x1 * math.sin(angle) - distance)/math.cos(angle))) + size[1] / 2
162     x2 = size[0] / 2 
163     y2 = int(round((x2 * math.sin(angle) - distance)/math.cos(angle))) + size[1] / 2
164     return [(0, y1), (size[0] - 1, y2)]
165
166 if __name__ == '__main__':
167     sys.exit(main())