peak extraction
[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     hough2 = Hough(im_h2.size)
81     im_hough2 = hough2.transform(im_h2)
82     if show_all:
83         do_something(im_hough2, "second hough transform")
84
85     im_h3 = filters.high_pass(im_hough2, 120)
86     if show_all:
87         do_something(im_h3, "third high pass filters")
88      
89     lines = hough2.find_angle_distance(im_h3)
90
91     im_lines = Image.new('L', im_h2.size)
92
93     draw = ImageDraw.Draw(im_lines)
94
95     for line in lines:
96         draw.line(line_from_angl_dist(line, im_h2.size), fill=255)
97     if show_all:
98         do_something(im_lines, "lines")
99
100     im_c = combine(im_h2, im_lines)
101     if show_all:
102         do_something(im_c, "first hough x lines")
103
104     collapse(im_c)
105     if show_all:
106         do_something(im_c, "optimalised hough")
107
108     lines = hough1.all_lines(im_c)
109     draw = ImageDraw.Draw(image)
110     for line in lines:
111         draw.line(line_from_angl_dist(line, image.size), fill=(120, 255, 120))
112
113     do_something(image, "the grid")
114
115     return 0
116
117 def image_save(image, title=''):
118     global Saving_dir
119     global Saving_num
120     filename = Saving_dir + "{0:0>2}".format(Saving_num) + '.jpg'
121     if not os.path.isdir(Saving_dir):
122         os.makedirs(Saving_dir)
123     image.save(filename, 'JPEG')
124     Saving_num += 1
125
126 def collapse(image):
127     #HACK
128     im_l = image.load()
129     last = False
130     for y in xrange(image.size[1]):
131         for x in xrange(image.size[0]):
132             if im_l[x, y] and last:
133                 im_l[x, y] = 0
134                 last = False
135             elif im_l[x, y]:
136                 last = True
137             elif last:
138                 last = False
139
140 def combine(image1, image2):
141     im_l1 = image1.load()
142     im_l2 = image2.load()
143
144     im_n = Image.new('L', image1.size)
145     im_nl = im_n.load()
146
147     for x in xrange(image1.size[0]):
148         for y in xrange(image1.size[1]):
149             if im_l1[x, y] and im_l2[x, y]:
150                 im_nl[x, y] = 255
151     return im_n
152
153 def line_from_angl_dist((angle, distance), size):
154     x1 = - size[0] / 2
155     y1 = int(round((x1 * math.sin(angle) - distance)/math.cos(angle))) + size[1] / 2
156     x2 = size[0] / 2 
157     y2 = int(round((x2 * math.sin(angle) - distance)/math.cos(angle))) + size[1] / 2
158     return [(0, y1), (size[0] - 1, y2)]
159
160 if __name__ == '__main__':
161     sys.exit(main())