cut.py 1.3 KB

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