1 | """ |
---|

2 | Utilities for manipulating bounding boxes as a tuple (llx, lly, urx, ury) |
---|

3 | |
---|

4 | @note: This has no connection with the cows data model. This module |
---|

5 | will probably move eventually. |
---|

6 | |
---|

7 | """ |
---|

8 | |
---|

9 | def intersection(bbox1, bbox2): |
---|

10 | """ |
---|

11 | Return a bbox of the intersection of bbox1 and bbox2. |
---|

12 | |
---|

13 | """ |
---|

14 | llx = max(bbox1[0], bbox2[0]) |
---|

15 | lly = max(bbox1[1], bbox2[1]) |
---|

16 | urx = min(bbox1[2], bbox2[2]) |
---|

17 | ury = min(bbox1[3], bbox2[3]) |
---|

18 | |
---|

19 | return llx, lly, urx, ury |
---|

20 | |
---|

21 | def relativeSize(bbox1, bbox2): |
---|

22 | """ |
---|

23 | Calculate the relative size of bbox1 to bbox2. |
---|

24 | |
---|

25 | @return: (sx, sy) where bbox1_width = sx * bbox2_width, etc. |
---|

26 | |
---|

27 | """ |
---|

28 | sx = (bbox1[2]-bbox1[0]) / (bbox2[2]-bbox2[0]) |
---|

29 | sy = (bbox1[3]-bbox1[1]) / (bbox2[3]-bbox2[1]) |
---|

30 | |
---|

31 | return (sx, sy) |
---|

32 | |
---|

33 | def geoToPixel(x_g, y_g, bbox, width, height): |
---|

34 | """ |
---|

35 | Calculate the pixel coordinate of a point within a bbox given the |
---|

36 | width and height of the bbox in pixels. |
---|

37 | |
---|

38 | This algorithm takes the origin of the bbox as the bottom left and |
---|

39 | the origin of the image as top left. |
---|

40 | |
---|

41 | @param x_g: x coordinate in goegraphic coordinates |
---|

42 | @param y_g: y coordinate in geographic coordinates |
---|

43 | @param bbox: The bounding box of the image |
---|

44 | @param width: The width of the image in pixels |
---|

45 | @param height: The height of the image in pixels. |
---|

46 | @return: (x,y) in pixel coordinates |
---|

47 | |
---|

48 | """ |
---|

49 | |
---|

50 | x = (x_g - bbox[0])*width / (bbox[2]-bbox[0]) |
---|

51 | y = (bbox[3] - y_g)*height / (bbox[3]-bbox[1]) |
---|

52 | |
---|

53 | return int(x), int(y) |
---|

54 | |
---|

55 | def pixelToGeo(x, y, bbox, width, height): |
---|

56 | """ |
---|

57 | Calculate the geographic coordinates of a pixel on an image |
---|

58 | of given bbox and size. |
---|

59 | |
---|

60 | This algorithm takes the origin of the bbox as the bottom left and |
---|

61 | the origin of the image as top left. |
---|

62 | |
---|

63 | @param x: x coordinate in pixel coordinates |
---|

64 | @param y: y coordinate in pixel coordinates |
---|

65 | @param bbox: The bounding box of the image |
---|

66 | @param width: The width of the image in pixels |
---|

67 | @param height: The height of the image in pixels. |
---|

68 | |
---|

69 | @return: (x_g, y_g) in geographic coordinates |
---|

70 | |
---|

71 | """ |
---|

72 | |
---|

73 | x_g = bbox[0] + ((bbox[2]-bbox[0]) / width)*x |
---|

74 | y_g = bbox[3] - ((bbox[3]-bbox[1]) / height)*y |
---|

75 | |
---|

76 | return (x_g, y_g) |
---|