e2c2876b694bad1f90d5b23aa63cd49546b45b35
[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('-S', '--sgf', dest='sgf_output', action='store_true',
39                         help="output in SGF")
40     parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
41                         help="report progress")
42     return parser
43  
44
45 def main():
46     """Main function of the program."""
47     
48     parser = argument_parser()
49     args = parser.parse_args()
50
51     show_all = args.show_all
52     verbose = args.verbose
53
54     try:
55         image = Image.open(args.files[0])
56     except IOError, msg:
57         print >> sys.stderr, msg
58         return 1
59     if image.mode == 'P':
60         image = image.convert('RGB')
61     
62     if image.size[0] > args.w:
63         image = image.resize((args.w, int((float(args.w)/image.size[0]) *
64                               image.size[1])), Image.ANTIALIAS)
65     do_something = im_debug.show
66     if args.saving:
67         do_something = Imsave("saved/" + args.files[0][:-4] + "_" +
68                                str(image.size[0]) + "/").save
69
70     if args.manual_mode:
71         try:
72             lines = manual.find_lines(image)
73         except manual.UserQuitError:
74             #TODO ask user to try again
75             return 1
76     else:
77         if args.l_cache:
78             filename = ("saved/cache/" + args.files[0][:-4] + "_" +
79                        str(image.size[0]))
80             cache_dir = "/".join(filename.split('/')[:-1])
81             if os.path.exists(filename):
82                 lines, l1, l2, bounds, hough = pickle.load(open(filename))
83                 print >> sys.stderr, "using cached results"
84                 im_h = None
85             else:
86                 lines, l1, l2, bounds, hough, im_h = linef.find_lines(image, show_all, do_something, verbose)
87                 if not os.path.isdir(cache_dir):
88                     os.makedirs(cache_dir)
89                 d_file = open(filename, 'wb')
90                 pickle.dump((lines, l1, l2, bounds, hough), d_file)
91                 d_file.close()
92         else:
93             lines, l1, l2, bounds, hough, im_h = linef.find_lines(image, show_all, do_something, verbose)
94
95         grid, lines = gridf.find(lines, image.size, l1, l2, bounds, hough,
96                                  show_all, do_something)
97         if show_all:
98             im_g = image.copy()
99             draw = ImageDraw.Draw(im_g)
100             for l in grid[0] + grid[1]:
101                 draw.line(l, fill=(64, 255, 64), width=1)
102             do_something(im_g, "grid", name="grid")
103
104     board = intrsc.board(image, lines, show_all, do_something)
105
106     if len(args.files) == 1:
107
108         if args.sgf_output:
109             print board.asSGFsetPos()
110         else:
111             print board
112     
113     else:
114         for f in args.files[1:]:
115             try:
116                 image = Image.open(f)
117             except IOError, msg:
118                 print >> sys.stderr, msg
119                 continue
120             if image.mode == 'P':
121                 image = image.convert('RGB')
122             board = intrsc.board(image, lines, show_all, do_something)
123             for line in board:
124                 print ' '.join(line)
125
126     return 0
127
128 class Imsave():
129     def __init__(self, saving_dir):
130         self.saving_dir = saving_dir
131         self.saving_num = 0
132
133     def save(self, image, title='', name=None):
134         if name:
135             filename = self.saving_dir + name + '.jpg'
136         else:
137             filename = self.saving_dir + "{0:0>2}".format(self.saving_num) + '.jpg'
138             self.saving_num += 1
139         if not os.path.isdir(self.saving_dir):
140             os.makedirs(self.saving_dir)
141         image.save(filename, 'JPEG')
142
143 if __name__ == '__main__':
144     try:
145         sys.exit(main())
146     except KeyboardInterrupt: #TODO does this work?
147         print "Interrupted."
148         sys.exit(1)