Last active
May 8, 2018 07:31
-
-
Save mdiener21/7adf4a0b27df3b21d10a3152408e5bb6 to your computer and use it in GitHub Desktop.
Find the center of a set of points using this bounding box class in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class BoundingBox(coordinate_list): | |
| """ | |
| Return a 2D bounding box from a set of points | |
| Example input: mypoints = [(0,2),(3,4),(5,6)] | |
| Example Usage: BoundingBox(mypoints) | |
| Example Usage: bbox = BoundingBox(mypoints) | |
| bbox.width | |
| bbox.height | |
| bbox.centroid | |
| """ | |
| def __init__(self, points): | |
| if len(points) == 0: | |
| raise ValueError("Can't compute bounding box of empty list") | |
| self.minx, self.miny = float("inf"), float("inf") | |
| self.maxx, self.maxy = float("-inf"), float("-inf") | |
| for x, y in points: | |
| # Set min coords | |
| if x < self.minx: | |
| self.minx = x | |
| if y < self.miny: | |
| self.miny = y | |
| # Set max coords | |
| if x > self.maxx: | |
| self.maxx = x | |
| elif y > self.maxy: | |
| self.maxy = y | |
| @property | |
| def width(self): | |
| return self.maxx - self.minx | |
| @property | |
| def height(self): | |
| return self.maxy - self.miny | |
| @property | |
| def centroid(self): | |
| xdist = (self.maxx - self.minx)/2.0 +self.minx | |
| ydist = (self.maxy - self.miny)/2.0 +self.miny | |
| return [xdist, ydist] | |
| def __repr__(self): | |
| return (self.minx, self.miny, self.maxx, self.maxy) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment