Python get bounding box
60 Python code examples are found related to "
get bounding box".
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: image_process.py From PyMIC with Apache License 2.0 | 8 votes |
def get_ND_bounding_box(volume, margin = None): """ get the bounding box of nonzero region in an ND volume """ input_shape = volume.shape if(margin is None): margin = [0] * len(input_shape) assert(len(input_shape) == len(margin)) indxes = np.nonzero(volume) idx_min = [] idx_max = [] for i in range(len(input_shape)): idx_min.append(indxes[i].min()) idx_max.append(indxes[i].max() + 1) for i in range(len(input_shape)): idx_min[i] = max(idx_min[i] - margin[i], 0) idx_max[i] = min(idx_max[i] + margin[i], input_shape[i]) return idx_min, idx_max
Example 2
Source File: utils.py From satpy with GNU General Public License v3.0 | 7 votes |
def get_geostationary_bounding_box(geos_area, nb_points=50): """Get the bbox in lon/lats of the valid pixels inside *geos_area*. Args: nb_points: Number of points on the polygon """ xmax, ymax = get_geostationary_angle_extent(geos_area) # generate points around the north hemisphere in satellite projection # make it a bit smaller so that we stay inside the valid area x = np.cos(np.linspace(-np.pi, 0, nb_points // 2)) * (xmax - 0.001) y = -np.sin(np.linspace(-np.pi, 0, nb_points // 2)) * (ymax - 0.001) # clip the projection coordinates to fit the area extent of geos_area ll_x, ll_y, ur_x, ur_y = (np.array(geos_area.area_extent) / float(geos_area.proj_dict['h'])) x = np.clip(np.concatenate([x, x[::-1]]), min(ll_x, ur_x), max(ll_x, ur_x)) y = np.clip(np.concatenate([y, -y]), min(ll_y, ur_y), max(ll_y, ur_y)) return _lonlat_from_geos_angle(x, y, geos_area)
Example 3
Source File: align_dlib.py From 1.FaceRecognition with MIT License | 7 votes |
def getLargestFaceBoundingBox(self, rgbImg, skipMulti=False): """ Find the largest face bounding box in an image. :param rgbImg: RGB image to process. Shape: (height, width, 3) :type rgbImg: numpy.ndarray :param skipMulti: Skip image if more than one face detected. :type skipMulti: bool :return: The largest face bounding box in an image, or None. :rtype: dlib.rectangle """ assert rgbImg is not None faces = self.getAllFaceBoundingBoxes(rgbImg) if (not skipMulti and len(faces) > 0) or len(faces) == 1: return max(faces, key=lambda rect: rect.width() * rect.height()) else: return None
Example 4
Source File: box_np_ops.py From second.pytorch with MIT License | 7 votes |
def get_minimum_bounding_box_bv(points, voxel_size, bound, downsample=8, margin=1.6): x_vsize = voxel_size[0] y_vsize = voxel_size[1] max_x = points[:, 0].max() max_y = points[:, 1].max() min_x = points[:, 0].min() min_y = points[:, 1].min() max_x = np.floor(max_x / (x_vsize * downsample) + 1) * (x_vsize * downsample) max_y = np.floor(max_y / (y_vsize * downsample) + 1) * (y_vsize * downsample) min_x = np.floor(min_x / (x_vsize * downsample)) * (x_vsize * downsample) min_y = np.floor(min_y / (y_vsize * downsample)) * (y_vsize * downsample) max_x = np.minimum(max_x + margin, bound[2]) max_y = np.minimum(max_y + margin, bound[3]) min_x = np.maximum(min_x - margin, bound[0]) min_y = np.maximum(min_y - margin, bound[1]) return np.array([min_x, min_y, max_x, max_y])
Example 5
Source File: GXMULTIGRID3D.py From gxpy with BSD 2-Clause "Simplified" License | 7 votes |
def get_bounding_box(self, min_x, min_y, min_z, max_x, max_y, max_z): """ Get the bounding box :param min_x: minx :param min_y: miny :param min_z: minz :param max_x: maxx :param max_y: maxy :param max_z: maxz :type min_x: float_ref :type min_y: float_ref :type min_z: float_ref :type max_x: float_ref :type max_y: float_ref :type max_z: float_ref .. versionadded:: 9.4 **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_ """ min_x.value, min_y.value, min_z.value, max_x.value, max_y.value, max_z.value = self._get_bounding_box(min_x.value, min_y.value, min_z.value, max_x.value, max_y.value, max_z.value)
Example 6
Source File: camlib.py From FlatCAM with MIT License | 7 votes |
def get_bounding_box(self, margin=0.0, rounded=False): """ Creates and returns a rectangular polygon bounding at a distance of margin from the object's ``solid_geometry``. If margin > 0, the polygon can optionally have rounded corners of radius equal to margin. :param margin: Distance to enlarge the rectangular bounding box in both positive and negative, x and y axes. :type margin: float :param rounded: Wether or not to have rounded corners. :type rounded: bool :return: The bounding box. :rtype: Shapely.Polygon """ bbox = self.solid_geometry.envelope.buffer(margin) if not rounded: bbox = bbox.envelope return bbox
Example 7
Source File: martinis.py From CrisisMappingToolkit with Apache License 2.0 | 7 votes |
def getBoundingBox(bounds): '''Returns (minLon, minLat, maxLon, maxLat) from domain bounds''' coordList = bounds['coordinates'][0] minLat = 999 minLon = 999999 maxLat = -999 maxLon = -999999 for c in coordList: if c[0] < minLon: minLon = c[0] if c[0] > maxLon: maxLon = c[0] if c[1] < minLat: minLat = c[1] if c[1] > maxLat: maxLat = c[1] return (minLon, minLat, maxLon, maxLat)
Example 8
Source File: Get_FLIR.py From computing-pipeline with BSD 3-Clause "New" or "Revised" License | 7 votes |
def get_bounding_box(center_position, fov): # NOTE: ZERO_ZERO is the southeast corner of the field. Position values increase to the northwest (so +y-position = +latitude, or more north and +x-position = -longitude, or more west) # We are also simplifying the conversion of meters to decimal degrees since we're not close to the poles and working with small distances. # NOTE: x --> latitude; y --> longitude try: r = 6378137 # earth's radius x_min = center_position[1] - fov[1]/2 x_max = center_position[1] + fov[1]/2 y_min = center_position[0] - fov[0]/2 y_max = center_position[0] + fov[0]/2 lat_min_offset = y_min/r* 180/pi lat_max_offset = y_max/r * 180/pi lng_min_offset = x_min/(r * cos(pi * ZERO_ZERO[0]/180)) * 180/pi lng_max_offset = x_max/(r * cos(pi * ZERO_ZERO[0]/180)) * 180/pi lat_min = ZERO_ZERO[0] - lat_min_offset lat_max = ZERO_ZERO[0] - lat_max_offset lng_min = ZERO_ZERO[1] - lng_min_offset lng_max = ZERO_ZERO[1] - lng_max_offset except Exception as ex: fail('Failed to get GPS bounds from center + FOV: ' + str(ex)) return (lat_max, lat_min, lng_max, lng_min)
Example 9
Source File: geometry.py From hwrt with MIT License | 7 votes |
def get_bounding_box(points: List[Dict[str, float]]) -> BoundingBox: """ Get the bounding box of a list of points. Parameters ---------- points : List[Dict[str, float]] Returns ------- BoundingBox """ assert len(points) > 0, "At least one point has to be given." min_x, max_x = points[0]["x"], points[0]["x"] min_y, max_y = points[0]["y"], points[0]["y"] for point in points: min_x, max_x = min(min_x, point["x"]), max(max_x, point["x"]) min_y, max_y = min(min_y, point["y"]), max(max_y, point["y"]) p1 = Point(min_x, min_y) p2 = Point(max_x, max_y) return BoundingBox(p1, p2)
Example 10
Source File: object.py From PyRep with MIT License | 7 votes |
def get_model_bounding_box(self) -> List[float]: """Gets the models bounding box (relative to models reference frame). :raises: ObjectIsNotModel if the object is not a model. :return: A list containing the min x, max x, min y, max y, min z, max z positions. """ self._check_model() params = [sim.sim_objfloatparam_modelbbox_min_x, sim.sim_objfloatparam_modelbbox_max_x, sim.sim_objfloatparam_modelbbox_min_y, sim.sim_objfloatparam_modelbbox_max_y, sim.sim_objfloatparam_modelbbox_min_z, sim.sim_objfloatparam_modelbbox_max_z] return [sim.simGetObjectFloatParameter( self._handle, p) for p in params]
Example 11
Source File: polygon.py From gdspy with Boost Software License 1.0 | 7 votes |
def get_bounding_box(self): """ Calculate the bounding box of the polygons. Returns ------- out : Numpy array[2, 2] or None Bounding box of this polygon in the form [[x_min, y_min], [x_max, y_max]], or None if the polygon is empty. """ if len(self.polygons) == 0: return None return numpy.array( ( ( min(pts[:, 0].min() for pts in self.polygons), min(pts[:, 1].min() for pts in self.polygons), ), ( max(pts[:, 0].max() for pts in self.polygons), max(pts[:, 1].max() for pts in self.polygons), ), ) )
Example 12
Source File: qt_occ_viewer.py From declaracad with GNU General Public License v3.0 | 7 votes |
def get_bounding_box(self, shapes): """ Compute the bounding box for the given list of shapes. Return values are in 3d coordinate space. Parameters ---------- shapes: List A list of TopoDS_Shape to compute a bbox for Returns ------- bbox: Tuple A tuple of (xmin, ymin, zmin, xmax, ymax, zmax). """ bbox = Bnd_Box() for shape in shapes: BRepBndLib.Add_(shape, bbox) try: pmin = bbox.CornerMin() pmax = bbox.CornerMax() except RuntimeError: return (0, 0, 0, 0, 0, 0) return (pmin.X(), pmin.Y(), pmin.Z(), pmax.X(), pmax.Y(), pmax.Z())
Example 13
Source File: geometry.py From pyresample with GNU Lesser General Public License v3.0 | 7 votes |
def get_geostationary_bounding_box(geos_area, nb_points=50): """Get the bbox in lon/lats of the valid pixels inside `geos_area`. Args: nb_points: Number of points on the polygon """ xmax, ymax = get_geostationary_angle_extent(geos_area) # generate points around the north hemisphere in satellite projection # make it a bit smaller so that we stay inside the valid area x = np.cos(np.linspace(-np.pi, 0, int(nb_points / 2.0))) * (xmax - 0.0001) y = -np.sin(np.linspace(-np.pi, 0, int(nb_points / 2.0))) * (ymax - 0.0001) ll_x, ll_y, ur_x, ur_y = geos_area.area_extent x *= geos_area.proj_dict['h'] y *= geos_area.proj_dict['h'] x = np.clip(np.concatenate([x, x[::-1]]), min(ll_x, ur_x), max(ll_x, ur_x)) y = np.clip(np.concatenate([y, -y]), min(ll_y, ur_y), max(ll_y, ur_y)) return Proj(**geos_area.proj_dict)(x, y, inverse=True)
Example 14
Source File: align_dlib.py From Python-Tensorflow-Face-v2.0 with Apache License 2.0 | 7 votes |
def getLargestFaceBoundingBox(self, rgbImg, skipMulti=False): """ Find the largest face bounding box in an image. :param rgbImg: RGB image to process. Shape: (height, width, 3) :type rgbImg: numpy.ndarray :param skipMulti: Skip image if more than one face detected. :type skipMulti: bool :return: The largest face bounding box in an image, or None. :rtype: dlib.rectangle """ assert rgbImg is not None faces = self.getAllFaceBoundingBoxes(rgbImg) if (not skipMulti and len(faces) > 0) or len(faces) == 1: return max(faces, key=lambda rect: rect.width() * rect.height()) else: return None
Example 15
Source File: layerHandler.py From DsgTools with GNU General Public License v2.0 | 7 votes |
def getFeaturesWithSameBoundingBox(self, iterator, isMulti, size, columns=None, feedback=None): """ Iterates over iterator and gets """ bbDict = defaultdict(list) for current, feat in enumerate(iterator): if feedback is not None and feedback.isCanceled(): break geom = feat.geometry() if isMulti and not geom.isMultipart(): geom.convertToMultiType() geomKey = geom.asWkb() geomBB_key = geom.boundingBox().asWktPolygon() attrKey = ','.join(['{}'.format(feat[column]) for column in columns]) if columns is not None else '' bbDict[geomBB_key].append({'geom':geom, 'feat':feat, 'attrKey':attrKey}) if feedback is not None: feedback.setProgress(size * current) return bbDict
Example 16
Source File: data_process.py From brats17 with BSD 3-Clause "New" or "Revised" License | 7 votes |
def get_ND_bounding_box(label, margin): """ get the bounding box of the non-zero region of an ND volume """ input_shape = label.shape if(type(margin) is int ): margin = [margin]*len(input_shape) assert(len(input_shape) == len(margin)) indxes = np.nonzero(label) idx_min = [] idx_max = [] for i in range(len(input_shape)): idx_min.append(indxes[i].min()) idx_max.append(indxes[i].max()) for i in range(len(input_shape)): idx_min[i] = max(idx_min[i] - margin[i], 0) idx_max[i] = min(idx_max[i] + margin[i], input_shape[i] - 1) return idx_min, idx_max
Example 17
Source File: wmo_file.py From Blender-WMO-import-export-scripts with GNU General Public License v3.0 | 7 votes |
def get_global_bounding_box(self): """ Calculate bounding box of an entire scene """ corner1 = self.mogi.Infos[0].BoundingBoxCorner1 corner2 = self.mogi.Infos[0].BoundingBoxCorner2 for gi in self.mogi.Infos: v = gi.BoundingBoxCorner1 if v[0] < corner1[0]: corner1[0] = v[0] if v[1] < corner1[1]: corner1[1] = v[1] if v[2] < corner1[2]: corner1[2] = v[2] v = gi.BoundingBoxCorner2 if v[0] > corner2[0]: corner2[0] = v[0] if v[1] > corner2[1]: corner2[1] = v[1] if v[2] > corner2[2]: corner2[2] = v[2] return corner1, corner2
Example 18
Source File: wmo_file.py From Blender-WMO-import-export-scripts with GNU General Public License v3.0 | 7 votes |
def get_object_bounding_box(self, obj): """ Calculate bounding box of an object """ corner1 = [0.0, 0.0, 0.0] corner2 = [0.0, 0.0, 0.0] for v in obj.bound_box: if v[0] < corner1[0]: corner1[0] = v[0] if v[1] < corner1[1]: corner1[1] = v[1] if v[2] < corner1[2]: corner1[2] = v[2] if v[0] > corner2[0]: corner2[0] = v[0] if v[1] > corner2[1]: corner2[1] = v[1] if v[2] > corner2[2]: corner2[2] = v[2] return (corner1, corner2)
Example 19
Source File: DebugVariableGraphicViewer.py From OpenPLC_Editor with GNU General Public License v3.0 | 7 votes |
def GetAxesBoundingBox(self, parent_coordinate=False): """ Return figure bounding box in wx coordinate @param parent_coordinate: True if use parent coordinate (default False) """ # Calculate figure bounding box. Y coordinate is inverted in matplotlib # figure comparing to wx panel width, height = self.GetSize() ax, ay, aw, ah = self.figure.gca().get_position().bounds bbox = wx.Rect(ax * width, height - (ay + ah) * height - 1, aw * width + 2, ah * height + 1) # If parent_coordinate, add Viewer position in parent if parent_coordinate: xw, yw = self.GetPosition() bbox.x += xw bbox.y += yw return bbox
Example 20
Source File: box_np_ops.py From Det3D with Apache License 2.0 | 7 votes |
def get_minimum_bounding_box_bv(points, voxel_size, bound, downsample=8, margin=1.6): x_vsize = voxel_size[0] y_vsize = voxel_size[1] max_x = points[:, 0].max() max_y = points[:, 1].max() min_x = points[:, 0].min() min_y = points[:, 1].min() max_x = np.floor(max_x / (x_vsize * downsample) + 1) * (x_vsize * downsample) max_y = np.floor(max_y / (y_vsize * downsample) + 1) * (y_vsize * downsample) min_x = np.floor(min_x / (x_vsize * downsample)) * (x_vsize * downsample) min_y = np.floor(min_y / (y_vsize * downsample)) * (y_vsize * downsample) max_x = np.minimum(max_x + margin, bound[2]) max_y = np.minimum(max_y + margin, bound[3]) min_x = np.maximum(min_x - margin, bound[0]) min_y = np.maximum(min_y - margin, bound[1]) return np.array([min_x, min_y, max_x, max_y])
Example 21
Source File: __init__.py From blender-terrain with GNU General Public License v3.0 | 7 votes |
def getSelectionBoundingBox(context): # perform context.scene.update(), otherwise o.matrix_world or o.bound_box are incorrect context.scene.update() if len(context.selected_objects)==0: return None xmin = float("inf") ymin = float("inf") xmax = float("-inf") ymax = float("-inf") for o in context.selected_objects: for v in o.bound_box: (x,y,z) = o.matrix_world * mathutils.Vector(v) if x<xmin: xmin = x elif x>xmax: xmax = x if y<ymin: ymin = y elif y>ymax: ymax = y return {"xmin": xmin, "ymin": ymin, "xmax": xmax, "ymax": ymax}
Example 22
Source File: base.py From BAG_framework with BSD 3-Clause "New" or "Revised" License | 7 votes |
def get_bounding_box(self, grid, layer=-1): """Calculate the overall bounding box of this port on the given layer. Parameters ---------- grid : :class:`~bag.layout.routing.RoutingGrid` the RoutingGrid of this Port. layer : int the layer ID. If Negative, check if this port is on a single layer, then return the result. Returns ------- bbox : BBox the bounding box. """ layer = self._get_layer(layer) box = BBox.get_invalid_bbox() for geo in self._pin_dict[layer]: if isinstance(geo, BBox): box = box.merge(geo) else: box = box.merge(geo.get_bbox_array(grid).get_overall_bbox()) return box
Example 23
Source File: generate_scene_obj.py From pySceneNetRGBD with GNU General Public License v3.0 | 7 votes |
def get_bounding_box(shapenet_path): shapenet_obj_file = open(shapenet_path, "r") vertices = [] for l in shapenet_obj_file: if l.startswith('v '): s = l[2:].split() x = float(s[0]) y = float(s[1]) z = float(s[2]) vertices.append([x, y, z]) min_x = min([v[0] for v in vertices]) max_x = max([v[0] for v in vertices]) min_y = min([v[1] for v in vertices]) max_y = max([v[1] for v in vertices]) min_z = min([v[2] for v in vertices]) max_z = max([v[2] for v in vertices]) return min_x, max_x, min_y, max_y, min_z, max_z
Example 24
Source File: extract_hand_from_PASCAL.py From image_utility with MIT License | 7 votes |
def get_bounding_box_from(xml_file, record_count): """ Find the hand bounding box from xml file and apped to xml value with meta info. """ tree = ET.parse(xml_file) root = tree.getroot() records = [] for member in root.findall('object'): if member[0].text == "person": for human_part in member.findall('part'): if human_part[0].text == "hand": record = (root.find('filename').text, int(root.find('size').find('width').text), int(root.find('size').find('height').text), human_part[0].text, int(human_part[1][0].text), int(human_part[1][1].text), int(human_part[1][2].text), int(human_part[1][3].text)) records.append(record) record_count += 1 return (records, record_count)
Example 25
Source File: shape_utils.py From oldnyc with Apache License 2.0 | 7 votes |
def GetShapeBoundingBox(shape): """Returns a {x, y, w, h} dict. (x, y) is the NW corner.""" x, y = shape.points[0] x_low, x_high = x, x y_low, y_high = y, y for x, y in shape.points[1:]: x_low = min(x, x_low) x_high = max(x, x_high) y_low = min(y, y_low) y_high = max(y, y_high) return { 'x': x_low, 'w': x_high - x_low, 'y': y_low, 'h': y_high - y_low }
Example 26
Source File: distorter.py From MathSymbolRecognizer with GNU General Public License v3.0 | 7 votes |
def getBoundingBox(self, points): min_x = points[0][0] max_x = points[0][0] min_y = points[0][1] max_y = points[0][1] for i in range(1, len(points)): x, y = points[i] if x < min_x: min_x = x if x > max_x: max_x = x if y < min_y: min_y = y if y > max_y: max_y = y return (min_x, max_x, min_y, max_y)
Example 27
Source File: BoundingBoxes.py From Object-Detection-Metrics with MIT License | 6 votes |
def getBoundingBoxByClass(self, classId): boundingBoxes = [] for d in self._boundingBoxes: if d.getClassId() == classId: # get only specified bounding box type boundingBoxes.append(d) return boundingBoxes
Example 28
Source File: SceneNode.py From Uranium with GNU Lesser General Public License v3.0 | 6 votes |
def getBoundingBox(self) -> Optional[AxisAlignedBox]: """Get the bounding box of this node and its children.""" if not self._calculate_aabb: return None if self._aabb is None: self._calculateAABB() return self._aabb
Example 29
Source File: LicModel.py From lic with GNU General Public License v3.0 | 6 votes |
def getBoundingBox(self, excluded=None): """ excluded is instance of QStringList and contains AbstractPart.filename This parameter is useful when part as base plate or other must be ignored to properly calculate of dimensions of model. """ if self._boundingBox and excluded is None: return self._boundingBox box = None for primitive in self.primitives: p = primitive.getBoundingBox() if p: if box: box.growByBoudingBox(p) else: box = p.duplicate() for part in self.parts: if excluded and excluded.contains(part.filename, cs=Qt.CaseInsensitive): continue else: p = part.abstractPart.getBoundingBox(excluded) if p: if box: box.growByBoudingBox(p, part.matrix) else: box = p.duplicate(part.matrix) if excluded is None: self._boundingBox = box return box
Example 30
Source File: bbox_quad_panda3d_env.py From citysim3d with MIT License | 6 votes |
def get_bounding_box(mask_image): rows = np.any(mask_image, axis=1) cols = np.any(mask_image, axis=0) rmin, rmax = np.where(rows)[0][[0, -1]] cmin, cmax = np.where(cols)[0][[0, -1]] return np.array([cmin, rmin]), np.array([cmax, rmax])
Example 31
Source File: tools.py From argoverse_baselinetracker with MIT License | 6 votes |
def get_bounding_box_3d( pc ): # gives 10 parameters: p0, p1, p2, p3 = p0 + (p1-p0)x(p2-p0) mins = pc.min(axis=0) maxs = pc.max(axis=0) p0 = mins[:, np.newaxis] p1 = np.array([maxs[0], mins[1], mins[2]])[:, np.newaxis] p2 = np.array([mins[0], maxs[1], mins[2]])[:, np.newaxis] H = maxs[2] - mins[2] return [p0, p1, p2, H]
Example 32
Source File: nexustiles.py From incubator-sdap-nexus with Apache License 2.0 | 6 votes |
def get_bounding_box(self, tile_ids): """ Retrieve a bounding box that encompasses all of the tiles represented by the given tile ids. :param tile_ids: List of tile ids :return: shapely.geometry.Polygon that represents the smallest bounding box that encompasses all of the tiles """ tiles = self.find_tiles_by_id(tile_ids, fl=['tile_min_lat', 'tile_max_lat', 'tile_min_lon', 'tile_max_lon'], fetch_data=False, rows=len(tile_ids)) polys = [] for tile in tiles: polys.append(box(tile.bbox.min_lon, tile.bbox.min_lat, tile.bbox.max_lon, tile.bbox.max_lat)) return box(*MultiPolygon(polys).bounds)
Example 33
Source File: spriteManager.py From universalSmashSystem with GNU General Public License v3.0 | 6 votes |
def getBoundingBox(self): bounding_rect = self.image.get_bounding_rect() bounding_rect.top += self.rect.top bounding_rect.left += self.rect.left return bounding_rect
Example 34
Source File: obstacle.py From pylot with Apache License 2.0 | 6 votes |
def get_bounding_box_corners(self, obstacle_transform, obstacle_radius=None): """Gets the corners of the obstacle's bounding box. Note: The bounding box is applied on the given obstacle transfom, and not on the default obstacle transform. """ # Use 3d bounding boxes if available, otherwise use default if isinstance(self.bounding_box, BoundingBox3D): start_location = (self.bounding_box.transform.location - self.bounding_box.extent) end_location = (self.bounding_box.transform.location + self.bounding_box.extent) [start_location, end_location] = obstacle_transform.transform_locations( [start_location, end_location]) else: obstacle_radius_loc = pylot.utils.Location(obstacle_radius, obstacle_radius) start_location = obstacle_transform.location - obstacle_radius_loc end_location = obstacle_transform.location + obstacle_radius_loc return [ min(start_location.x, end_location.x), min(start_location.y, end_location.y), max(start_location.x, end_location.x), max(start_location.y, end_location.y) ]
Example 35
Source File: util.py From bot with GNU General Public License v3.0 | 6 votes |
def get_bounding_box( latitude_in_degrees, longitude_in_degrees, half_side_in_miles, logger ): if half_side_in_miles == 0: logger.error("Check your Radius its lower then 0") return {} if latitude_in_degrees < -90.0 or latitude_in_degrees > 90.0: logger.error("Check your latitude should be between -90/90") return {} if longitude_in_degrees < -180.0 or longitude_in_degrees > 180.0: logger.error("Check your longtitude should be between -180/180") return {} half_side_in_km = half_side_in_miles * 1.609344 lat = radians(latitude_in_degrees) lon = radians(longitude_in_degrees) radius = 6371 # Radius of the parallel at given latitude parallel_radius = radius * cos(lat) lat_min = lat - half_side_in_km / radius lat_max = lat + half_side_in_km / radius lon_min = lon - half_side_in_km / parallel_radius lon_max = lon + half_side_in_km / parallel_radius lat_min = rad2deg(lat_min) lon_min = rad2deg(lon_min) lat_max = rad2deg(lat_max) lon_max = rad2deg(lon_max) bbox = { "lat_min": lat_min, "lat_max": lat_max, "lon_min": lon_min, "lon_max": lon_max, } return bbox
Example 36
Source File: segmentation.py From director with BSD 3-Clause "New" or "Revised" License | 6 votes |
def getOrientedBoundingBox(polyData): ''' returns origin, edges, and outline wireframe ''' nPoints = polyData.GetNumberOfPoints() assert nPoints polyData = shallowCopy(polyData) labelsArrayName = 'bbox_labels' labels = np.ones(nPoints) vtkNumpy.addNumpyToVtk(polyData, labels, labelsArrayName) f = vtk.vtkAnnotateOBBs() f.SetInputArrayToProcess(0,0,0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, labelsArrayName) f.SetInputData(polyData) f.Update() assert f.GetNumberOfBoundingBoxes() == 1 origin = np.zeros(3) edges = [np.zeros(3) for i in range(3)] f.GetBoundingBoxOrigin(0, origin) for i in range(3): f.GetBoundingBoxEdge(0, i, edges[i]) return origin, edges, shallowCopy(f.GetOutput())
Example 37
Source File: no_rendering_mode.py From scenario_runner with MIT License | 6 votes |
def get_bounding_box(actor): bb = actor.trigger_volume.extent corners = [carla.Location(x=-bb.x, y=-bb.y), carla.Location(x=bb.x, y=-bb.y), carla.Location(x=bb.x, y=bb.y), carla.Location(x=-bb.x, y=bb.y), carla.Location(x=-bb.x, y=-bb.y)] corners = [x + actor.trigger_volume.location for x in corners] t = actor.get_transform() t.transform(corners) return corners # ============================================================================== # -- ModuleManager ------------------------------------------------------------- # ==============================================================================
Example 38
Source File: BoundingBox.py From Object-Detection-Metrics with MIT License | 6 votes |
def getRelativeBoundingBox(self, imgSize=None): if imgSize is None and self._width_img is None and self._height_img is None: raise IOError( 'Parameter \'imgSize\' is required. It is necessary to inform the image size.') if imgSize is None: return convertToRelativeValues((imgSize[0], imgSize[1]), (self._x, self._y, self._w, self._h)) else: return convertToRelativeValues((self._width_img, self._height_img), (self._x, self._y, self._w, self._h))
Example 39
Source File: BoundingBox.py From GAN_Review with MIT License | 6 votes |
def getAbsoluteBoundingBox(self, format=BBFormat.XYWH): if format == BBFormat.XYWH: return (self._x, self._y, self._w, self._h) elif format == BBFormat.XYX2Y2: return (self._x, self._y, self._x2, self._y2)
Example 40
Source File: DAVIS_instance.py From PReMVOS with MIT License | 6 votes |
def get_bounding_box(mask, inst): mask = np.copy(mask) rows = np.where(mask == inst)[0] cols = np.where(mask == inst)[1] rmin = rows.min() rmax = rows.max() cmin = cols.min() cmax = cols.max() mask[rmin:rmax, cmin:cmax] = 1.0 return mask
Example 41
Source File: ev_charging_stations_api.py From HerePy with MIT License | 6 votes |
def get_stations_bounding_box(self, top_left: List[float], bottom_right: List[float], connectortypes: List[EVStationConnectorTypes]=None): """Makes a search request for charging stations with in given bounding box. The bounding box can have a maximum height / width of 400km. Args: top_left (array): array including latitude and longitude in order. bottom_right (array): array including latitude and longitude in order. connectortypes (List[EVStationConnectorTypes]): Optional, to identify the connector types. Returns: EVChargingStationsResponse Raises: HEREError """ if connectortypes: connector_types_str = self.__connector_types_str(connectortypes) data = {'app_id': self._app_id, 'app_code': self._app_code, 'bbox': str.format('{0},{1};{2},{3}', top_left[0], top_left[1], bottom_right[0], bottom_right[1]), 'connectortype': connector_types_str} else: data = {'app_id': self._app_id, 'app_code': self._app_code, 'bbox': str.format('{0},{1};{2},{3}', top_left[0], top_left[1], bottom_right[0], bottom_right[1])} response = self.__get(self._base_url + 'stations.json', data, EVChargingStationsResponse) return response
Example 42
Source File: bounding_box.py From scholar-reader with Apache License 2.0 | 6 votes |
def get_symbol_bounding_box( symbol: Symbol, symbol_id: SymbolId, token_boxes: TokenLocations ) -> Optional[BoundingBox]: boxes = [] for token_index in symbol.tokens: token_id = TokenId( symbol_id.tex_path, symbol_id.equation_index, token_index ) boxes.extend(token_boxes.get(token_id, [])) if len(boxes) == 0: return None # Boxes for a symbol should be on only one page. if len({box.page for box in boxes}) > 1: logging.warning( # pylint: disable=logging-not-lazy ( "Boxes found on more than one page for symbol %s. " + "Only the boxes for one page will be considered." ), symbol, ) page = boxes[0].page boxes_on_page = list(filter(lambda b: b.page == page, boxes)) left = min([box.left for box in boxes_on_page]) right = max([box.left + box.width for box in boxes_on_page]) top = min([box.top for box in boxes_on_page]) bottom = max([box.top + box.height for box in boxes_on_page]) return BoundingBox(left, top, right - left, bottom - top, page)
Example 43
Source File: mathSymbol.py From CROHME_2014 with GNU General Public License v3.0 | 6 votes |
def getSquaredBoundingBox(self): #start with first trace... minX, maxX, minY, maxY = self.traces[0].getBoundaries() #expand if other traces need it for i in range(1, len(self.traces)): oMinX, oMaxX, oMinY, oMaxY = self.traces[i].getBoundaries() #min X if oMinX < minX: minX = oMinX #max X if oMaxX > maxX: maxX = oMaxX #min Y if oMinY < minY: minY = oMinY #max Y if oMaxY > maxY: maxY = oMaxY #the original proportions must be keep, check longest side... width = maxX - minX height = maxY - minY if width > height: #keep minX, maxX, move Y bounds to keep proportions inside a square minY = ((maxY + minY) / 2.0) - (width / 2.0) maxY = minY + width else: #keep minY, maxY, move X bounds to keep proportions inside a square minX = ((maxX + minX) / 2.0) - (height / 2.0) maxX = minX + height return [minX, maxX, minY, maxY] #normalize the symbol
Example 44
Source File: html.py From pgu with GNU Lesser General Public License v2.1 | 6 votes |
def get_bounding_box(this): minx = miny = sys.maxsize maxx = maxy = -sys.maxsize for e in this.layout.widgets: minx = min(minx, e.rect.left) miny = min(miny, e.rect.top) maxx = max(maxx, e.rect.right+1) maxy = max(maxy, e.rect.bottom+1) return pygame.Rect(minx, miny, maxx-minx, maxy-miny)
Example 45
Source File: mapclient_qt.py From CrisisMappingToolkit with Apache License 2.0 | 6 votes |
def GetMapBoundingBox(self): """Return the bounding box of the current view as [minLon, minLat, maxLon, maxLat]""" # Just get the coordinates of the pixel corners of the map image topLeftLonLat = self.pixelCoordToLonLat(0, 0) botRightLonLat = self.pixelCoordToLonLat(self.width(), self.height()) return [topLeftLonLat[0], botRightLonLat[1], botRightLonLat[0], topLeftLonLat[1]]
Example 46
Source File: data_manipulation.py From waldo with Apache License 2.0 | 6 votes |
def get_minimum_bounding_box(polygon): """ Given a list of points, returns a minimum area rectangle that will contain all points. It will not necessarily be vertically or horizontally aligned. Returns ------- list((int, int)): 4 corner points of rectangle. """ validate_polygon(polygon) points_list = get_mar(polygon) validate_polygon(points_list) return points_list
Example 47
Source File: calculate_bounding_boxes.py From pdfCropMargins with GNU General Public License v3.0 | 6 votes |
def get_bounding_box_list(input_doc_fname, input_doc, full_page_box_list, set_of_page_nums_to_crop, argparse_args, chosen_PdfFileWriter): """Calculate a bounding box for each page in the document. The `input_doc_fname` argument is the filename of the document's original PDF file, the second is the PdfFileReader for the document. The argument full_page_box_list is a list of the full-page-size boxes (which is used to correct for any nonzero origins in the PDF coordinates). The set_of_page_nums_to_crop argument is the set of page numbers to crop; it is passed so that unnecessary calculations can be skipped. The argparse_args argument should be passed the args parsed from the command line by argparse. The chosen_PdfFileWriter is the PdfFileWriter class from whichever pyPdf package was chosen by the main program. The function returns the list of bounding boxes.""" global args, page_nums_to_crop, PdfFileWriter args = argparse_args # Make args available to all funs in module, as a global. page_nums_to_crop = set_of_page_nums_to_crop # Make the set of pages global, too. PdfFileWriter = chosen_PdfFileWriter # Be sure correct PdfFileWriter is set. if args.gsBbox: if args.verbose: print("\nUsing Ghostscript to calculate the bounding boxes.") bbox_list = ex.get_bounding_box_list_ghostscript(input_doc_fname, args.resX, args.resY, args.fullPageBox) else: if not hasPIL: print("\nError in pdfCropMargins: No version of the PIL package (or a" "\nfork like Pillow) was found. Either install that Python" "\npackage or use the Ghostscript flag '--gsBbox' (or '-gs') if you" "\nhave Ghostscript installed.", file=sys.stderr) ex.cleanup_and_exit(1) bbox_list = get_bounding_box_list_render_image(input_doc_fname, input_doc) # Now we need to use the full page boxes to translate for non-zero origin. bbox_list = correct_bounding_box_list_for_nonzero_origin(bbox_list, full_page_box_list) return bbox_list
Example 48
Source File: airbnb_survey.py From airbnb-data-collection with MIT License | 6 votes |
def get_bounding_box(self): try: # Get the bounding box conn = self.config.connect() cur = conn.cursor() cur.execute(""" select bb_n_lat, bb_e_lng, bb_s_lat, bb_w_lng from search_area sa join survey s on sa.search_area_id = s.search_area_id where s.survey_id = %s""", (self.survey_id,)) # result comes back as a tuple. We want it mutable later, so # convert to a list [n_lat, e_lng, s_lat, w_lng] bounding_box = list(cur.fetchone()) cur.close() # Validate the bounding box if None in bounding_box: logger.error("Invalid bounding box: contains 'None'") return None if bounding_box[0] <= bounding_box[2]: logger.error("Invalid bounding box: n_lat must be > s_lat") return None if bounding_box[1] <= bounding_box[3]: logger.error("Invalid bounding box: e_lng must be > w_lng") return None return bounding_box except Exception: logger.exception("Exception in set_bounding_box") self.bounding_box = None
Example 49
Source File: base.py From MDT with GNU Lesser General Public License v3.0 | 6 votes |
def get_bounding_box(self, dimension, slice_index, volume_index, rotate, map_names=None): """Get the bounding box of the images. Args: dimension (int): the dimension to search in slice_index (int): the slice index in that dimension volume_index (int): the current volume index rotate (int): the angle by which to rotate the image before getting the bounding box map_names (list of str): if given we will only scan the given list of maps Returns: tuple of :class:`Point2d`: two points designating the upper left corner and the lower right corner of the bounding box. """ raise NotImplementedError()
Example 50
Source File: utils.py From axidraw-xy with MIT License | 6 votes |
def get_bounding_box(xy): mi = xy.min(axis=0).squeeze() ma = xy.max(axis=0).squeeze() xd = ma[0]-mi[0] yd = ma[1]-mi[1] return mi, ma, xd, yd
Example 51
Source File: utils.py From tobac with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_bounding_box(x,buffer=1): from numpy import delete,arange,diff,nonzero,array """ Calculates the bounding box of a ndarray https://stackoverflow.com/questions/31400769/bounding-box-of-numpy-array """ mask = x == 0 bbox = [] all_axis = arange(x.ndim) #loop over dimensions for kdim in all_axis: nk_dim = delete(all_axis, kdim) mask_i = mask.all(axis=tuple(nk_dim)) dmask_i = diff(mask_i) idx_i = nonzero(dmask_i)[0] # for case where there is no value in idx_i if len(idx_i) == 0: idx_i=array([0,x.shape[kdim]-1]) # for case where there is only one value in idx_i elif len(idx_i) == 1: idx_i=array([idx_i,idx_i]) # make sure there is two values in idx_i elif len(idx_i) > 2: idx_i=array([idx_i[0],idx_i[-1]]) # caluclate min and max values for idx_i and append them to list idx_min=max(0,idx_i[0]+1-buffer) idx_max=min(x.shape[kdim]-1,idx_i[1]+1+buffer) bbox.append([idx_min, idx_max]) return bbox
Example 52
Source File: render.py From gym-carla with MIT License | 6 votes |
def get_bounding_box(actor): bb = actor.trigger_volume.extent corners = [carla.Location(x=-bb.x, y=-bb.y), carla.Location(x=bb.x, y=-bb.y), carla.Location(x=bb.x, y=bb.y), carla.Location(x=-bb.x, y=bb.y), carla.Location(x=-bb.x, y=-bb.y)] corners = [x + actor.trigger_volume.location for x in corners] t = actor.get_transform() t.transform(corners) return corners