RAPP Platform  v0.6.0
RAPP Platform is a collection of ROS nodes and back-end processes that aim to deliver ready-to-use generic services to robots
 All Classes Namespaces Files Functions Variables Macros
crop_map.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 import sys
4 import yaml
5 from PIL import Image
6 import math
7 
8 def find_bounds(map_image):
9  x_min = map_image.size[0]
10  x_end = 0
11  y_min = map_image.size[1]
12  y_end = 0
13  pix = map_image.load()
14  for x in range(map_image.size[0]):
15  for y in range(map_image.size[1]):
16  val = pix[x, y]
17  if val != 205: # not unknown
18  x_min = min(x, x_min)
19  x_end = max(x, x_end)
20  y_min = min(y, y_min)
21  y_end = max(y, y_end)
22  return x_min, x_end, y_min, y_end
23 
24 def computed_cropped_origin(map_image, bounds, resolution, origin):
25  """ Compute the image for the cropped map when map_image is cropped by bounds and had origin before. """
26  ox = origin[0]
27  oy = origin[1]
28  oth = origin[2]
29 
30  # First figure out the delta we have to translate from the lower left corner (which is the origin)
31  # in the image system
32  dx = bounds[0] * resolution
33  dy = (map_image.size[1] - bounds[3]) * resolution
34 
35  # Next rotate this by the theta and add to the old origin
36 
37  new_ox = ox + dx * math.cos(oth) - dy * math.sin(oth)
38  new_oy = oy + dx * math.sin(oth) + dy * math.cos(oth)
39 
40  return [new_ox, new_oy, oth]
41 
42 if __name__ == "__main__":
43  if len(sys.argv) < 2:
44  print >> sys.stderr, "Usage: %s map.yaml [cropped.yaml]" % sys.argv[0]
45  sys.exit(1)
46 
47  with open(sys.argv[1]) as f:
48  map_data = yaml.safe_load(f)
49 
50  if len(sys.argv) > 2:
51  crop_name = sys.argv[2]
52  if crop_name.endswith(".yaml"):
53  crop_name = crop_name[:-5]
54  crop_yaml = crop_name + ".yaml"
55  crop_image = crop_name + ".pgm"
56  else:
57  crop_yaml = "cropped.yaml"
58  crop_image = "cropped.pgm"
59 
60  map_image_file = map_data["image"]
61  resolution = map_data["resolution"]
62  origin = map_data["origin"]
63 
64  map_image = Image.open(map_image_file)
65 
66  bounds = find_bounds(map_image)
67 
68  # left, upper, right, lower
69  cropped_image = map_image.crop((bounds[0], bounds[2], bounds[1] + 1, bounds[3] + 1))
70 
71  cropped_image.save(crop_image)
72  map_data["image"] = crop_image
73  map_data["origin"] = computed_cropped_origin(map_image, bounds, resolution, origin)
74  with open(crop_yaml, "w") as f:
75  yaml.dump(map_data, f)
76 
def computed_cropped_origin
Definition: crop_map.py:24
def find_bounds
Definition: crop_map.py:8