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