def read_irs(self, x, y, o, r, objects): # data vis_sensors_domain = [] ir_reading = [] # for each sensor for ir_angle in self.ir_angles: ir_val = 0 min_dist = self.ray_length # location and orientation according to agent ir_o = geometry.force_angle(o + ir_angle) ir_x = x + r * np.cos(ir_o) ir_y = y + r * np.sin(ir_o) # define visual domain arc_start = ir_o + self.beam_angles[0] arc_end = ir_o + self.beam_angles[1] # to be sure the angle is counter-clockwise if arc_start > arc_end: arc_end += np.radians(360) # get arc angle points and force angles arc_points = np.linspace(arc_start, arc_end, self.s_points) arc_angles = np.array( [geometry.force_angle(oi) for oi in arc_points]) # get the arc coordinates and create polygon arc_x = ir_x + self.ray_length * np.cos(arc_angles) arc_y = ir_y + self.ray_length * np.sin(arc_angles) vis_coords = [(ir_x, ir_y)] [vis_coords.append((xi, yi)) for xi, yi in zip(arc_x, arc_y)] vis_domain = Polygon(vis_coords) vis_sensors_domain.append(vis_domain) # check for intersections for w in objects["walls"]: wall = LineString([(w.xmin, w.ymin), (w.xmax, w.ymax)]) if vis_domain.intersects(wall): dist = Point(ir_x, ir_y).distance(vis_domain.intersection(wall)) if dist < min_dist: min_dist = dist round_objects = objects["trees"] + objects["agents"] for obj in round_objects: obj_loc = Point(obj.x, obj.y) obj_space = obj_loc.buffer(obj.r) if vis_domain.intersects(obj_space): dist = Point(ir_x, ir_y).distance( vis_domain.intersection(obj_space)) if dist < min_dist: min_dist = dist # get ir value if min_dist < self.ray_length: # IR reading for a given distance from empirical fitting data # gaussian 3371*e^(-(d/8.5)^2) fits well [0, 3500] k = -1 * ((dist / 8.5)**2) ir_val = (3371 * np.exp(k)) / 3500 ir_reading.append(ir_val) self.sensory_domain["vis"].append(vis_sensors_domain) return ir_reading
def is_coords_in_box(coords, patch_size, boxes): """Get area of annotation in patch. Parameters ---------- coords:array X,Y coordinates of patch. patch_size:int Patch size. boxes:list Shapely objects for annotations. Returns ------- float Area of annotation type. """ if len(boxes): points = Polygon( np.array([[0, 0], [1, 0], [1, 1], [0, 1]]) * patch_size + coords) area = points.intersection( boxes[0] ).area #any(list(map(lambda x: x.intersects(points),boxes)))#return_image_coord(nx=nx,ny=ny,xi=xi,yi=yi, output_point=output_point) else: area = 0. return area
def read_olf(self, x, y, o, r, objects): # sensor location-orientation olf_x = x + r * np.cos(o) olf_y = y + r * np.sin(o) olf_val = 0 # define sensor domain (polygon) arc_start = o + self.olf_angles[0] arc_end = o + self.olf_angles[1] # to be sure the angle is counter-clockwise if arc_start > arc_end: arc_end += np.radians(360) # get arc angle points and force angles arc_points = np.linspace(arc_start, arc_end, self.s_points) arc_angles = np.array([geometry.force_angle(oi) for oi in arc_points]) # get the arc coordinates and create polygon arc_x = olf_x + self.olf_range * np.cos(arc_angles) arc_y = olf_y + self.olf_range * np.sin(arc_angles) olf_coords = [(olf_x, olf_y)] [olf_coords.append((xi, yi)) for xi, yi in zip(arc_x, arc_y)] olf_domain = Polygon(olf_coords) self.sensory_domain["olf"].append(olf_domain) # check for each tree min_dist = self.olf_range trees = objects["trees"] for tx in trees: tree_loc = Point(tx.x, tx.y) tree_space = tree_loc.buffer(tx.r) if olf_domain.intersects(tree_space): dist = Point(olf_x, olf_y).distance( olf_domain.intersection(tree_space)) if dist <= min_dist: olf_val = (1 / np.exp(min_dist / self.olf_range))**2 return olf_val
def determine_imageOverlap(f1, f2, plotsave=False, verbose=False, debugmode=False, quietmode=False): ''' Determine the max number of pixels in AXIS1 and AXIS2 of the input fits images, print to screen unless suppressed. Plot up the footprint if -p option is on. Right now, only takes in 2 fits images (YOLO).''' # Read in f1,f2 d1, h1 = fits.getdata(f1, header=True) d2, h2 = fits.getdata(f2, header=True) w1 = wcs.WCS(h1) w2 = wcs.WCS(h2) # Get the RA and DEC coordinates of the four corners of each image four_corners_RADECs1 = get_cornerRADECs(f1) four_corners_RADECs2 = get_cornerRADECs(f2) # Get polygon of each image corners poly1 = Polygon(four_corners_RADECs1) poly2 = Polygon(four_corners_RADECs2) # Get intersection polygon poly_intersect = poly1.intersection(poly2) # Get RA DEC of corners of the intersection (overlapping) polygon x_intersect, y2_intersect = poly_intersect.exterior.xy # Get intersection RA and DEC. # Note that the last coordinate is a repeat of the first, so remove it. corner_RADECs_intersect = np.transpose( np.array([x_intersect[0:-1], y2_intersect[0:-1]])) # Do pixel scale checks: are pixels square, are pixel scales of two images similar enough # Exits if input images found to be outside what this is coded for; Prints warnings if in debugmode but not exiting. perform_pixelscaleChecks(w1, w2, verbose=verbose, debugmode=debugmode) # Get XLEN and YLEN- Diff pix scales give diff XLEN, YLEN for same RA,DEC range # Get the average XLEN and YLEN for the two input image pixscales XLEN1, YLEN1 = get_imagesize(corner_RADECs_intersect, w1) XLEN2, YLEN2 = get_imagesize(corner_RADECs_intersect, w2) if verbose: print(f'XLEN1,YLEN1: {XLEN1},{YLEN1}') print(f'XLEN2,YLEN2: {XLEN2},{YLEN2}') #XLEN = int(np.average([XLEN1,XLEN2])) # auto floor #YLEN = int(np.average([YLEN1,YLEN2])) # auto floor XLEN = min([XLEN1, XLEN2]) # Take the smallest YLEN = min([YLEN1, YLEN2]) # Take the smallest # Print information if not quiet mode, or if verbose if not quietmode and not verbose: print(f'-IMAGE_SIZE option in SWarp can be set to: {XLEN},{YLEN}') printme = f'SWarp Command to align two images: swarp {f1} {f2} -SUBTRACT_BACK N -RESAMEPLE Y -COMBINE N -CENTER_TYPE MOST -IMAGE_SIZE {XLEN},{YLEN} -RESAMPLE_DIR ./' print_verbose_string(printme, verbose=verbose) # If plotsave, plot and save. if plotsave: plot_polygonOverlap(poly1, poly2, quietmode=quietmode) return XLEN, YLEN
def get_iou_cuboid(cu1, cu2): """ Calculate the Intersection over Union (IoU) of two 3D cuboid. Parameters ---------- cu1 : numpy array, 8x3 cu2 : numpy array, 8x3 Returns ------- float in [0, 1] """ polygon_1 = Polygon([(cu1[0][0], cu1[0][1]), (cu1[1][0], cu1[1][1]), (cu1[2][0], cu1[2][1]), (cu1[3][0], cu1[3][1])]) polygon_2 = Polygon([(cu2[0][0], cu2[0][1]), (cu2[1][0], cu2[1][1]), (cu2[2][0], cu2[2][1]), (cu2[3][0], cu2[3][1])]) intersect_2d = polygon_1.intersection(polygon_2).area inter_vol = intersect_2d * max( 0.0, min(cu1[0][2], cu2[0][2]) - max(cu1[4][2], cu2[4][2])) vol1 = polygon_1.area * (cu1[0][2] - cu1[4][2]) vol2 = polygon_2.area * (cu2[0][2] - cu2[4][2]) return inter_vol / (vol1 + vol2 - inter_vol)
def roi_overlap(ROIs1, ROIs2, param1, param2, im1_shape, im2_shape, thr_ovlp=0.5, pplot=False, im1=None): """ rotate/translate rois ROI1 and ROI2 by parameters param1 and param2, and then test which ROIs overlap """ ROIs1_trans = rottrans_rois(ROIs1, param1[0], param1[1], param1[2], im1_shape[0], im1_shape[1]) ROIs2_trans = rottrans_rois(ROIs2, param2[0], param2[1], param2[2], im2_shape[0], im2_shape[1]) # NOTE: for plotting the variable im1 is missing if pplot: plt.figure() axes = plt.subplot(111) axes.imshow(im1, cmap='gray') draw_rois(ROIs1, axes, 'red') draw_rois(ROIs2_trans, axes, 'green') plt.show(block=False) # test which ROIs overlap ri = 0 roi_map = {} for r in ROIs1_trans: (x0, y0) = (r[0][0], r[1][0]) polyg1 = Polygon(list(zip(r[0], r[1])) + [(x0, y0)]) si = 0 for s in ROIs2_trans: (x0, y0) = (s[0][0], s[1][0]) polyg2 = Polygon(list(zip(s[0], s[1])) + [(x0, y0)]) if polyg1.intersects(polyg2): p = polyg1.intersection(polyg2) if (p.area >= polyg1.area * thr_ovlp) or ( p.area >= polyg2.area * thr_ovlp): #if roi_map.has_key(ri): if ri in roi_map: roi_map[ri].append(si) else: roi_map[ri] = [si] si = si + 1 ri = ri + 1 for r in list(roi_map.keys()): if len(roi_map[r]) > 1: roi_map.pop(r, None) roi_map = [(k, roi_map[k][0]) for k in roi_map.keys()] return roi_map
def get_iou_cuboid(cu1, cu2): """ Calculate the Intersection over Union (IoU) of two 3D cuboid. Parameters ---------- cu1 : numpy array, 8x3 cu2 : numpy array, 8x3 Returns ------- float in [0, 1] """ # 2D projection on the horizontal plane (x-y plane) polygon2D_1 = Polygon( [(cu1[0][0], cu1[0][1]), (cu1[1][0], cu1[1][1]), (cu1[2][0], cu1[2][1]), (cu1[3][0], cu1[3][1])]) polygon2D_2 = Polygon( [(cu2[0][0], cu2[0][1]), (cu2[1][0], cu2[1][1]), (cu2[2][0], cu2[2][1]), (cu2[3][0], cu2[3][1])]) # 2D intersection area of the two projections. intersect_2D = polygon2D_1.intersection(polygon2D_2).area # the volume of the intersection part of cu1 and cu2 inter_vol = intersect_2D * max(0.0, min(cu1[4][2], cu2[4][2]) - max(cu1[0][2], cu2[0][2])) # the volume of cu1 and cu2 vol1 = polygon2D_1.area * (cu1[4][2] - cu1[0][2]) vol2 = polygon2D_2.area * (cu2[4][2] - cu2[0][2]) # return 3D IoU return inter_vol / (vol1 + vol2 - inter_vol)
def intersection_cuboid(cu1, cu2): polygon_1 = Polygon([(cu1[0][0], cu1[0][1]), (cu1[1][0], cu1[1][1]), (cu1[2][0], cu1[2][1]), (cu1[3][0], cu1[3][1])]) polygon_2 = Polygon([(cu2[0][0], cu2[0][1]), (cu2[1][0], cu2[1][1]), (cu2[2][0], cu2[2][1]), (cu2[3][0], cu2[3][1])]) intersection_2d = polygon_1.intersection(polygon_2).area if min(cu1[0][2], cu2[0][2]) - max(cu1[4][2], cu2[4][2]) > 0: return (min(cu1[0][2], cu2[0][2]) - max(cu1[4][2], cu2[4][2])) * intersection_2d else: return 0
def intersection_2d_ratio(cu1, cu2): polygon_1 = Polygon([(cu1[0][0], cu1[0][1]), (cu1[1][0], cu1[1][1]), (cu1[2][0], cu1[2][1]), (cu1[3][0], cu1[3][1])]) polygon_2 = Polygon([(cu2[0][0], cu2[0][1]), (cu2[1][0], cu2[1][1]), (cu2[2][0], cu2[2][1]), (cu2[3][0], cu2[3][1])]) intersection_ratio = polygon_1.intersection( polygon_2).area / polygon_1.area return intersection_ratio
def iou_2dobj(bbx_pred, bbx_gt): ''' A error metric in terms of 2d object :param bbx_pred: 8*2 :param bbx_gt: 4*2 :return: the iou of bbx_pred and bbx_gt ''' hull_pred = ConvexHull(bbx_pred) bbx_gt = np.array([[bbx_gt[0], bbx_gt[1]], [bbx_gt[2], bbx_gt[1]], [bbx_gt[0], bbx_gt[3]], [bbx_gt[2], bbx_gt[3]]]) hull_gt = ConvexHull(bbx_gt) polygon_gt = Polygon([(bbx_gt[ind, 0], bbx_gt[ind, 1]) for ind in hull_gt.vertices]) polygon_pred = Polygon([(bbx_pred[ind, 0], bbx_pred[ind, 1]) for ind in hull_pred.vertices]) visualize = False if visualize: plt.plot(bbx_pred[:, 0], bbx_pred[:, 1], 'o') in_area = polygon_gt.intersection(polygon_pred) x, y = in_area.exterior.xy plt.plot(x, y, color='#6699cc', alpha=0.7, linewidth=3, solid_capstyle='round', zorder=2) un_area = polygon_gt.union(polygon_pred) x, y = un_area.exterior.xy plt.plot(x, y, color='#6699cc', alpha=0.7, linewidth=3, solid_capstyle='round', zorder=2) for simplex in hull_gt.simplices: plt.plot(bbx_gt[simplex, 0], bbx_gt[simplex, 1], 'k-') for simplex in hull_pred.simplices: plt.plot(bbx_pred[simplex, 0], bbx_pred[simplex, 1], 'k-') plt.show() iou = polygon_gt.intersection(polygon_pred).area / polygon_gt.union( polygon_pred).area return iou
def get_iou_cuboid(cu1, cu2): polygon_1 = Polygon([cu1[0], cu1[1], cu1[2], cu1[3]]) polygon_2 = Polygon([cu2[0], cu2[1], cu2[2], cu2[3]]) intersect_2d = polygon_1.intersection(polygon_2).area inter_vol = intersect_2d * max(0.0, min(cu1[5], cu2[5]) - max(cu1[4], cu2[4])) vol1 = polygon_1.area * (cu1[5] - cu1[4]) vol2 = polygon_2.area * (cu2[5] - cu2[4]) return inter_vol / (vol1 + vol2 - inter_vol + 0.00001)
def is_valid_polygon(self, triangle): for key in self.save_data.keys(): obstacles = Polygon(self.save_data[key]) polygon_intersection = obstacles.intersection(triangle).area polygon_union = obstacles.union(triangle).area IOU = polygon_intersection / polygon_union if IOU > 0: return False return True
def intersection_over_layout(cu1, cu2): polygon_1 = Polygon([(cu1[0][0], cu1[0][1]), (cu1[1][0], cu1[1][1]), (cu1[2][0], cu1[2][1]), (cu1[3][0], cu1[3][1])]) polygon_2 = Polygon([(cu2[0][0], cu2[0][1]), (cu2[1][0], cu2[1][1]), (cu2[2][0], cu2[2][1]), (cu2[3][0], cu2[3][1])]) intersection_2d = polygon_1.intersection(polygon_2).area if min(cu1[0][2], cu2[0][2]) - max(cu1[4][2], cu2[4][2]) > 0: # return (polygon_1.area - intersection_2d) * (min(cu1[0][2], cu2[0][2]) - max(cu1[4][2], cu2[4][2])) return (polygon_1.area - intersection_2d) * 0.1 else: # return polygon_1.area * (cu1[0][2] - cu1[4][2]) return polygon_1.area * 0.1
def compare_tile_segment(coordinates, tile, image_dir, tile_images_directory): """ Compares whether the box bounded by the tile's original coordinates intersects the tumor segment indicated in the xml file. Saves all tiles images. Arguments: coordinates: a list of tumor segments coordinates from xml annotations tile: the tile being investigated image_dir: directory of original WSI files tile_images_directory: directory to which images of tiles will be saved Returns: Depending on the positivity of the tile: - if positive tumor: returns the coordinates on that tile image of the tumor region(s) - if negative: returns None, None values """ box = Box(tile.o_c_s, tile.o_r_s, tile.o_c_e, tile.o_r_e) for i in range(len(coordinates)): # We disregard coordinates with less than 2 xy values if len(coordinates[i]) < 3: continue if not os.path.exists(tile_images_directory + tile.file_title + "_" + str(tile.tile_num) + '.png'): save_tile_image(tile, image_dir, tile_images_directory) print(tile.file_title + "_", str(tile.tile_num) + ".png image saved") segment = Polygon(coordinates[i]) if segment.intersects(box): segment = transform(reflection(1), segment) box = transform(reflection(1), box) try: overlap = segment.intersection(box) except: print("Error in ", tile.file_title, " num: ", tile.tile_num, " coord index: ", i) continue if isinstance(overlap, MultiPolygon): x_overlap_shifted_list = [] y_overlap_shifted_list = [] for element in overlap: x_overlap_shifted, y_overlap_shifted = get_xy(tile, element) x_overlap_shifted_list.append(x_overlap_shifted) y_overlap_shifted_list.append(y_overlap_shifted) return x_overlap_shifted_list, y_overlap_shifted_list else: x_overlap_shifted, y_overlap_shifted = get_xy(tile, overlap) return x_overlap_shifted, y_overlap_shifted else: continue return None, None
def get_bounds(radius, max_offset): x_bound = 2 * radius y_max, y_min = 2 * radius, -(max_offset + radius) bounding_box = Polygon([(-x_bound, y_min), (x_bound, y_min), (x_bound, y_max), (-x_bound, y_max)]) center = (0, radius) bounding_circle = Point(*center).buffer(2 * radius + max_offset) outer_bound = Point(*center).buffer(GratingEllipse.max_radius) interior = bounding_box.intersection(bounding_circle) bounding_curve = outer_bound.difference(interior) return bounding_curve
def get_intersection_geometry(self, rect, ref_geom): min_x, min_y, max_x, max_y = rect tile_ulp = (min_x, max_y) tile_dlp = (min_x, min_y) tile_drp = (max_x, min_y) tile_urp = (max_x, max_y) tile = Polygon([tile_ulp, tile_dlp, tile_drp, tile_urp]) poly_int = tile.intersection(ref_geom) if not poly_int.is_empty: return poly_int
def compute_intersect_features(input_file, output_file): input_f = open(input_file) output_f = open(output_file, 'w') line = input_f.readline() output_f.writelines( '{},intersection_area1,intersection_area2,jaccard_similarity\n'.format( line.strip())) line = input_f.readline() while line: # Extract mbr of 2 datasets data = line.strip().split(',') dataset1_x1, dataset1_y1, dataset1_x2, dataset1_y2 = float( data[15]), float(data[16]), float(data[17]), float(data[18]) dataset2_x1, dataset2_y1, dataset2_x2, dataset2_y2 = float( data[32]), float(data[33]), float(data[34]), float(data[35]) dataset1_mbr = Polygon([(dataset1_x1, dataset1_y1), (dataset1_x1, dataset1_y2), (dataset1_x2, dataset1_y2), (dataset1_x2, dataset1_y1)]) dataset2_mbr = Polygon([(dataset2_x1, dataset2_y1), (dataset2_x1, dataset2_y2), (dataset2_x2, dataset2_y2), (dataset2_x2, dataset2_y1)]) intersection_area1 = dataset1_mbr.intersection( dataset2_mbr).area / dataset1_mbr.area intersection_area2 = dataset1_mbr.intersection( dataset2_mbr).area / dataset2_mbr.area jaccard_similarity = dataset1_mbr.intersection( dataset2_mbr).area / dataset1_mbr.union(dataset2_mbr).area output_f.writelines('{},{},{},{}\n'.format(line.strip(), intersection_area1, intersection_area2, jaccard_similarity)) line = input_f.readline() output_f.close() input_f.close()
def get_polygons_areas(coordinates1, coordinates2): polygon1 = Polygon(coordinates1) polygon2 = Polygon(coordinates2) intersection = polygon1.intersection(polygon2) union = polygon1.union(polygon2) try: coordinates = intersection.exterior.xy except AttributeError: coordinates = [[0, 0, 0, 0], [0, 0, 0, 0]] return intersection.area, union.area, coordinates
def spans_feature(self, rect, ref_shape): min_x, min_y, max_x, max_y = rect tile_ulp = (min_x, max_y) tile_dlp = (min_x, min_y) tile_drp = (max_x, min_y) tile_urp = (max_x, max_y) tile = Polygon([tile_ulp, tile_dlp, tile_drp, tile_urp]) #return not tile.intersection(geom).is_empty for feature in ref_shape: shp_geom = shape(feature['geometry']) poly_int =tile.intersection(shp_geom) if not poly_int.is_empty: return True return False
def generate_raster_cuts(self, cut_name, required_modalities): for row_col, bb in self.tiles_bb.items(): region = Polygon(bb) for r in required_modalities: if r in self.mod_union: poly = self.mod_union[r] region = region.intersection(poly) else: region = None # modality did not exist if region is not None and not region.is_empty: print('intersection {} {}'.format(region.area, region)) for tf in self.tiles_files[row_col]: self.cut_raster(tf, os.path.splitext(tf)[0] + '_' + cut_name + '.tif', region) else: print('empty')
def reward2(pred, gt): if abs(pred[4].item()) >= 0.5: return 0 pred_poly = Polygon(extract_coord(pred)) gt_poly = Polygon(extract_coord(gt)) try: inter_area = pred_poly.intersection(gt_poly).area except TopologicalError: inter_area = 0 except ValueError: inter_area = 0 if not inter_area: return 0 else: return inter_area / (pred_poly.area + gt_poly.area - inter_area)
def getIntersectionArea(bldPoly,line,perpLine,bldID): if not line.intersects(bldPoly): return 0.0 pt1 = list(line.coords)[0] pt2 = list(line.coords)[1] perppt1 = list(perpLine.coords)[0] perppt2 = list(perpLine.coords)[1] dx = perppt2[0] - perppt1[0] dy = perppt2[1] - perppt1[1] pt3 = (pt1[0]-dx,pt1[1]-dy) pt4 = (pt2[0]-dx,pt2[1]-dy) linePoly = Polygon([pt1,pt3,pt4,pt2]) try: intersection_area = linePoly.intersection(bldPoly).area return intersection_area/bldPoly.area except: return -1
def hull_accuracy(problem, result, target): nzr = numpy.nonzero(result)[0] nzt = numpy.nonzero(target)[0] result = result[nzr] target = target[nzt] if len(result) < 3 or len(set(result)) != len(result): return -1.0, 0.0 pp = Polygon(problem[result]) if pp.is_valid: # intersected area tt = Polygon(problem[target]) intersection = tt.intersection(pp) intersec_per = intersection.area / tt.area if set(result) == set(target): return 1.0, intersec_per else: return 0.0, intersec_per else: return -1.0, 0.0
def delete_bbox_overlap(indexA, indexB, list_bbox, list_bbox_Copy): ''' indexA: index of bbox A indexB: index of bbox B if bbox A and bbox B overlap, detele the smallest ''' bboxA = list_bbox[indexA] bboxB = list_bbox[indexB] polygon_A = Polygon(bboxA) polygon_B = Polygon(bboxB) intersec_area = polygon_A.intersection(polygon_B).area area_polygonA = polygon_A.area area_polygonB = polygon_B.area ratio_overlap = intersec_area / min(area_polygonA, area_polygonB) if ratio_overlap >= 0.3 and area_polygonA < area_polygonB: if bboxA in list_bbox_Copy: list_bbox_Copy.remove(bboxA) elif ratio_overlap >= 0.3 and area_polygonA > area_polygonB: if bboxB in list_bbox_Copy: list_bbox_Copy.remove(bboxB)
def check_dem_overlap(opts, ring): """ Evaluate DEM overlap between existing and downloadable DEM """ from isce3.io import raster # Get local DEM edge coordinates mm = opts.margin DEM = raster(filename=opts.filepath) ulx, xres, xskew, uly, yskew, yres = DEM.GeoTransform lrx = ulx + (DEM.width * xres) lry = uly + (DEM.length * yres) minX, maxX, minY, maxY = getBbox(ring, DEM.EPSG) # Create the Polygons for both local and downloadable DEM Poly_dem = Polygon([(ulx, uly), (ulx, lry), (lrx, lry), (lrx, uly)]) Poly_ring = Polygon([(minX - mm, minY - mm), (minX - mm, maxY + mm), (maxX + mm, maxY + mm), (maxX + mm, minY - mm)]) perc_area = (Poly_ring.intersection(Poly_dem).area / Poly_ring.area) * 100 return perc_area
def GenerateMultipleWellConceptsTEST(input_gdf_polygons, n_concepts=100, lon_min=139.4, lon_max=140.0, lat_min=29.8, lat_max=30.5): '''Function generates a list of well concepts. Not that there is a slight workaround in this method, see below. Hence it has been labelled TEST Parameters ---------- input_gdf_polygons GeoDataFrame with a polygon geometry column n_concepts Number of well concepts to return Returns ------- list: [[WC Names], [WC Lat Lon], [WC Resource]] - where len([WC Names, WC Lat Lon and WC Resource ''' l = [] #BUG WORKAROUND FIX- Some polygons are invalid since first and last points are the same - they must not be. for p in input_gdf_polygons.polygon.values: if p.is_valid == True: l.append(p) # Union of all polygons targ_poly_union = cascaded_union(l) #Generate a polygon bounding box from the min and max of lon and lat bbox = Polygon([[lon_min, lat_min], [lon_min, lat_max], [lon_max, lat_max], [lon_max, lat_min]]) # Get all polygons within bbx bbox = bbox.intersection(targ_poly_union) #Generate Well Concepts WellConcepts = [GenerateWellConcept(bbox) for i in range(n_concepts)] return list(zip(*WellConcepts))
def _reduce_multi_pred(predictions): """ Reduces predictions with high overlapping area i.e. predictions for the same object, by removing all but the one with the highest confidence value. Args: predictions (list): A list of prediction dictionaries. Returns: list: A reduced list of prediction dictionaries. """ reduce = predictions.copy() # Iterate through all combinations of masks, comparing each only once for ((index_a, a), (index_b, b)) in itertools.combinations(enumerate(predictions), 2): a_polygon = Polygon(a['mask']) b_polygon = Polygon(b['mask']) # Calculate the intersection between the masks try: intersection = a_polygon.intersection(b_polygon).area except TopologicalError: continue # How much overlap exists between them smallest = min(a_polygon.area, b_polygon.area) overlap = intersection / smallest # If high overlap, remove the lower from the result if overlap > 0.8: if a['object_score'] > b['object_score']: reduce[index_b] = None else: reduce[index_a] = None ret = [x for x in reduce if x] return ret
def get_distance_iou_3d(x1: np.ndarray, x2: np.ndarray, name: str = "bbox") -> float: w1 = x1["width"] l1 = x1["length"] h1 = x1["height"] w2 = x2["width"] l2 = x2["length"] h2 = x2["height"] poly1 = Polygon([(-l1 / 2, -w1 / 2), (-l1 / 2, w1 / 2), (l1 / 2, w1 / 2), (l1 / 2, -w1 / 2)]) poly2 = Polygon([(-l2 / 2, -w2 / 2), (-l2 / 2, w2 / 2), (l2 / 2, w1 / 2), (l2 / 2, -w2 / 2)]) inter = poly1.intersection(poly2).area * min(h1, h2) union = w1 * l1 * h1 + w2 * l2 * h2 - inter score = 1 - inter / union return float(score)
class Pipe(object): def __init__(self, width, segment, linker): global pipe_count p1 = np.array(segment[0]) p4 = np.array(segment[1]) rot_matrix = np.array([[0,-1],[1,0]]) rot = rot_matrix.dot((p4 - p1)) p2 = p1 + rot/(np.linalg.norm(rot))*width p3 = p4 + rot/(np.linalg.norm(rot))*width pts = map(to_latlon,map(list,[p1,p2,p3,p4,p1])) self.pipe_count = pipe_count pipe_count += 1 pipes.poly(shapeType=shapefile.POLYLINE, parts=zip(list(pts[:-1]),list(pts[1:]))) pipes.record(self.pipe_count) self.polygon = Polygon([p1,p2,p3,p4]) def __contains__(self, building): building_poly = Polygon(building) try: intersection_area = self.polygon.intersection(building_poly).area return intersection_area/building_poly.area > 0.1 except: return False
if bool(ipix_inter): for ipix in ipix_inter: pixvec = hp.boundaries(nsideSparse, ipix, nest=True) #vertcies of healpix pixel polypix = Polygon(np.transpose(hp.vec2ang( np.transpose(pixvec)))) #polygon of healpix pixel if polyframe.contains(polypix): ind = np.where(ipix_infield == ipix)[0][0] nvisit[band][ind] += 1. for i, dataname in enumerate(datanames): mp[band][i][ind] += row[dataname] * 1. elif polyframe.intersects(polypix): ind = np.where(ipix_infield == ipix)[0][0] area = polyframe.intersection( polypix ).area / polypix.area #fraction of pixel inside visit frame nvisit[band][ind] += area for i, dataname in enumerate(datanames): mp[band][i][ind] += row[dataname] * area #write maps dtype = [(dataname, 'f8') for dataname in datanames] dtype.insert(0, ('nvisit', 'f8')) for b in bands: norm_mp = np.zeros(Nmpix, dtype=dtype) norm_mp['nvisit'][nvisit[b] > 0] = nvisit[b][nvisit[b] > 0] for i, dataname in enumerate(datanames): norm_mp[dataname][ nvisit[b] > 0] = mp[b][i][nvisit[b] > 0] / nvisit[b][nvisit[b] > 0] hsp_mp = hsp.HealSparseMap.makeEmpty(nsideCoverage,