| 1 | import sys |
| 2 | |
| 3 | athresh = 100 |
| 4 | border = 20 |
| 5 | |
| 6 | segf = sys.argv[1] |
| 7 | if len(sys.argv) > 2: |
| 8 | pref = sys.argv[2] |
| 9 | else: |
| 10 | pref = '/tmp/cut' |
| 11 | rects = [] |
| 12 | starts = {} |
| 13 | for l in file(segf).xreadlines(): |
| 14 | ls = l.split() |
| 15 | if len(ls) == 6 and ls[-1] == 'rect': |
| 16 | r = map(int, ls[:4]) |
| 17 | area = (r[2] - r[0]) * (r[3] - r[1]) |
| 18 | if area > athresh: |
| 19 | rpad = [r[0] - border, r[1] - border, r[2] + border, r[3] + border] |
| 20 | if not starts.has_key(rpad[1]): |
| 21 | starts[rpad[1]] = [] |
| 22 | starts[rpad[1]].append(len(rects)) |
| 23 | rects.append(rpad) |
| 24 | inf = sys.stdin |
| 25 | l = inf.readline() |
| 26 | if l != 'P5\n': |
| 27 | raise 'expected pgm file' |
| 28 | while 1: |
| 29 | l = inf.readline() |
| 30 | if l[0] != '#': break |
| 31 | x, y = map(int, l.split()) |
| 32 | l = inf.readline() |
| 33 | |
| 34 | active = {} |
| 35 | for j in range(y): |
| 36 | if starts.has_key(j): |
| 37 | for ix in starts[j]: |
| 38 | r = rects[ix] |
| 39 | ofn = pref + '%04d.pgm' % ix |
| 40 | of = file(ofn, 'w') |
| 41 | active[ix] = of |
| 42 | print >> of, 'P5' |
| 43 | print >> of, r[2] - r[0], r[3] - r[1] |
| 44 | print >> of, '255' |
| 45 | buf = inf.read(x) |
| 46 | for ix, of in active.items(): |
| 47 | r = rects[ix] |
| 48 | of.write(buf[r[0]:r[2]]) |
| 49 | if j == r[3] - 1: |
| 50 | of.close() |
| 51 | del active[ix] |
| 52 |