# source:cows/trunk/cows/bbox_util.py@4072

Revision 4072, 2.4 KB checked in by spascoe, 13 years ago (diff)

Improved bbox_util functionality.

RevLine
[3553]1"""
2Utilities for manipulating bounding boxes as a tuple (llx, lly, urx, ury)
3
[4008]4@note: This has no connection with the cows data model.  This module
[3553]5    will probably move eventually.
6
7"""
8
[4072]9import math
10
[3553]11def intersection(bbox1, bbox2):
12    """
13    Return a bbox of the intersection of bbox1 and bbox2.
14
15    """
16    llx = max(bbox1[0], bbox2[0])
17    lly = max(bbox1[1], bbox2[1])
18    urx = min(bbox1[2], bbox2[2])
19    ury = min(bbox1[3], bbox2[3])
20
21    return llx, lly, urx, ury
22
23def relativeSize(bbox1, bbox2):
24    """
25    Calculate the relative size of bbox1 to bbox2.
26
27    @return: (sx, sy) where bbox1_width = sx * bbox2_width, etc.
28
29    """
30    sx = (bbox1[2]-bbox1[0]) / (bbox2[2]-bbox2[0])
31    sy = (bbox1[3]-bbox1[1]) / (bbox2[3]-bbox2[1])
32
33    return (sx, sy)
34
[4072]35def geoToPixel(x_g, y_g, bbox, width, height, roundUpX=False, roundUpY=False):
[3553]36    """
37    Calculate the pixel coordinate of a point within a bbox given the
38    width and height of the bbox in pixels.
39
40    This algorithm takes the origin of the bbox as the bottom left and
41    the origin of the image as top left.
42
43    @param x_g: x coordinate in goegraphic coordinates
44    @param y_g: y coordinate in geographic coordinates
45    @param bbox: The bounding box of the image
46    @param width: The width of the image in pixels
47    @param height: The height of the image in pixels.
[4072]48    @param roundUpX: Round the X pixel value upwards.
49    @param roundUpY: Round the y pixel value upwards.
50
[3553]51    @return: (x,y) in pixel coordinates
52
53    """
54
55    x = (x_g - bbox[0])*width / (bbox[2]-bbox[0])
56    y = (bbox[3] - y_g)*height / (bbox[3]-bbox[1])
57
[4072]58    if roundUpX:
59        x = math.ceil(x)
60    if roundUpY:
61        y = math.ceil(y)
62
[3553]63    return int(x), int(y)
64
65def pixelToGeo(x, y, bbox, width, height):
66    """
67    Calculate the geographic coordinates of a pixel on an image
68    of given bbox and size.
69
70    This algorithm takes the origin of the bbox as the bottom left and
71    the origin of the image as top left.
72
73    @param x: x coordinate in pixel coordinates
74    @param y: y coordinate in pixel coordinates
75    @param bbox: The bounding box of the image
76    @param width: The width of the image in pixels
77    @param height: The height of the image in pixels.
78
79    @return: (x_g, y_g) in geographic coordinates
80
81    """
82
83    x_g = bbox[0] + ((bbox[2]-bbox[0]) / width)*x
84    y_g = bbox[3] - ((bbox[3]-bbox[1]) / height)*y
85
86    return (x_g, y_g)
Note: See TracBrowser for help on using the repository browser.