output module
[imago.git] / imago_pack / imago.py
1 #!/usr/bin/env python
2
3 """Go image recognition."""
4
5 import sys
6 import os
7 import argparse
8 import pickle
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 linef
18 import manual
19 import intrsc
20 import gridf
21
22 def argument_parser():
23     parser = argparse.ArgumentParser(description=__doc__)
24     parser.add_argument('files', metavar='file', nargs='+',
25                         help="image to analyse")
26     parser.add_argument('-w', type=int, default=640,
27                     help="scale image to the specified width before analysis")
28     parser.add_argument('-m', '--manual', dest='manual_mode',
29                         action='store_true',
30                         help="manual grid selection")
31     parser.add_argument('-d', '--debug', dest='show_all',
32                         action='store_true',
33                         help="show every step of the computation")
34     parser.add_argument('-s', '--save', dest='saving', action='store_true',
35                         help="save images instead of displaying them")
36     parser.add_argument('-c', '--cache', dest='l_cache', action='store_true',
37                         help="use cached lines")
38     parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
39                         help="report progress")
40     return parser
41  
42
43 def main():
44     """Main function of the program."""
45     
46     parser = argument_parser()
47     args = parser.parse_args()
48
49     show_all = args.show_all
50     verbose = args.verbose
51
52     try:
53         image = Image.open(args.files[0])
54     except IOError, msg:
55         print >> sys.stderr, msg
56         return 1
57     if image.mode == 'P':
58         image = image.convert('RGB')
59     
60     if image.size[0] > args.w:
61         image = image.resize((args.w, int((float(args.w)/image.size[0]) *
62                               image.size[1])), Image.ANTIALIAS)
63     do_something = im_debug.show
64     if args.saving:
65         do_something = Imsave("saved/" + args.files[0][:-4] + "_" +
66                                str(image.size[0]) + "/").save
67
68     if args.manual_mode:
69         try:
70             lines = manual.find_lines(image)
71         except manual.UserQuitError:
72             #TODO ask user to try again
73             return 1
74     else:
75         if args.l_cache:
76             filename = ("saved/cache/" + args.files[0][:-4] + "_" +
77                        str(image.size[0]))
78             cache_dir = "/".join(filename.split('/')[:-1])
79             if os.path.exists(filename):
80                 lines, l1, l2, bounds, hough = pickle.load(open(filename))
81                 print >> sys.stderr, "using cached results"
82                 im_h = None
83             else:
84                 lines, l1, l2, bounds, hough, im_h = linef.find_lines(image, show_all, do_something, verbose)
85                 if not os.path.isdir(cache_dir):
86                     os.makedirs(cache_dir)
87                 d_file = open(filename, 'wb')
88                 pickle.dump((lines, l1, l2, bounds, hough), d_file)
89                 d_file.close()
90         else:
91             lines, l1, l2, bounds, hough, im_h = linef.find_lines(image, show_all, do_something, verbose)
92
93         grid, lines = gridf.find(lines, image.size, l1, l2, bounds, hough,
94                                  show_all, do_something)
95         if show_all:
96             im_g = image.copy()
97             draw = ImageDraw.Draw(im_g)
98             for l in grid[0] + grid[1]:
99                 draw.line(l, fill=(64, 255, 64), width=1)
100             do_something(im_g, "grid", name="grid")
101
102     board = intrsc.board(image, lines, show_all, do_something)
103
104     #simple ASCII output:
105     print board
106     
107     if len(args.files) > 1:
108         for f in args.files[1:]:
109             try:
110                 image = Image.open(f)
111             except IOError, msg:
112                 print >> sys.stderr, msg
113                 continue
114             if image.mode == 'P':
115                 image = image.convert('RGB')
116             board = intrsc.board(image, lines, show_all, do_something)
117             for line in board:
118                 print ' '.join(line)
119
120     return 0
121
122 class Imsave():
123     def __init__(self, saving_dir):
124         self.saving_dir = saving_dir
125         self.saving_num = 0
126
127     def save(self, image, title='', name=None):
128         if name:
129             filename = self.saving_dir + name + '.jpg'
130         else:
131             filename = self.saving_dir + "{0:0>2}".format(self.saving_num) + '.jpg'
132             self.saving_num += 1
133         if not os.path.isdir(self.saving_dir):
134             os.makedirs(self.saving_dir)
135         image.save(filename, 'JPEG')
136
137 if __name__ == '__main__':
138     try:
139         sys.exit(main())
140     except KeyboardInterrupt: #TODO does this work?
141         print "Interrupted."
142         sys.exit(1)