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