Advertisement
Guest User

Draw a rectangle covering

a guest
Jan 17th, 2015
515
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.23 KB | None | 0 0
  1. # Draw a collection of rectangles.
  2. from PIL import Image, ImageDraw
  3.  
  4. GRID_SIZE = 15
  5. LINE_WIDTH = 2
  6. OUT_FILE = "out.png"
  7.  
  8. def main():
  9.     rects = map(lambda x: x if len(x) == 4 else x + (1,1), input())
  10.     min_x, max_x, min_y, max_y = 0, 0, 0, 0
  11.     for (x, y, w, h) in rects:
  12.         min_x = min(min_x, x)
  13.         max_x = max(max_x, x+w)
  14.         min_y = min(min_y, y)
  15.         max_y = max(max_y, y+h)
  16.     width = max_x - min_x + 2
  17.     height = max_y - min_y + 2
  18.     im = Image.new("RGB", (GRID_SIZE*width, GRID_SIZE*height), "white")
  19.     draw = ImageDraw.Draw(im)
  20.     for x in range(1,width):
  21.         for i in range(LINE_WIDTH):
  22.             draw.line([GRID_SIZE*x+i,0,GRID_SIZE*x+i,im.size[1]], fill=(0,0,0))
  23.     for y in range(1,height):
  24.         for j in range(LINE_WIDTH):
  25.             draw.line([0,GRID_SIZE*y+j,im.size[0],GRID_SIZE*y+j], fill=(0,0,0))
  26.     for (x, y, w, h) in rects:
  27.         draw.rectangle([(x-min_x+1)*GRID_SIZE+LINE_WIDTH,
  28.                         (y-min_y+1)*GRID_SIZE+LINE_WIDTH,
  29.                         (x+w-min_x+1)*GRID_SIZE-1,
  30.                         (y+h-min_y+1)*GRID_SIZE-1], fill=(255,0,0))
  31.     im = im.transpose(Image.FLIP_TOP_BOTTOM)
  32.     im.save(OUT_FILE)
  33.  
  34. if __name__ == "__main__":
  35.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement