def isSquare(shape, minPerimeter=0): """Returns the corners and center of a sqaure-like contour or false if not square-like.""" peri = cv2.arcLength(shape, True) corners = cv2.approxPolyDP(shape, 0.02 * peri, True) if len(corners) is 4 and peri > minPerimeter: # check shape is a quadrangle of useable size a = Point(corners[0][0][0], corners[0][0][1]) b = Point(corners[1][0][0], corners[1][0][1]) c = Point(corners[2][0][0], corners[2][0][1]) d = Point(corners[3][0][0], corners[3][0][1]) ab = a.distance(b) bc = b.distance(c) lineRatio = max((ab, bc)) / min((ab, bc)) if lineRatio < 2: # check that quadrangle is likely a square center = findCenter(a, b, c, d) return corners, center return False, False
def minimum_edge_length(polygon, plot_segments=False): min_size = np.inf #previous_point = Point(polygon.coords[-1]) for ip, point_tuple in enumerate(polygon.coords): point = Point(point_tuple) if ip == 0: previous_point = point continue distance = point.distance(previous_point) if plot_segments: line_string = LineString([previous_point, point]) plot_line_string(line_string, color='orange') if distance < min_size: min_size = distance previous_point = point return min_size
def update(self): targets = self.simulation.field.targets #print(targets) agents = self.simulation.agents.array mask = agents['active'] & ~agents['target_reached'] #print(np.sum(agents['active'])) #print(agents['target'][np.nonzero(agents['is_leader'])]) for i in range(len(agents)): if not mask[i]: continue x, y = agents[i]['position'] point = Point(x, y) for target, name in zip(targets, self.names): if point.distance(target) < self.epsilon: self.simulation.data[name] += 1 agents['target_reached'][i] = True agents['active'][i] = False
def CircleLineSegmentIntersections(circle, segment): center = Point(circle.center[0], circle.center[1]) distance = segment.distance(center) if distance > circle.radius + EPS: return [] super_point = ShortestToLine(segment, circle.center) super_point_p = Point(super_point[0], super_point[1]) orig_point = segment.coords[0] dest_point = segment.coords[1] dist = Point(orig_point[0], orig_point[1]).distance(super_point_p) if ((dest_point[0] - orig_point[0]) * (orig_point[0] - super_point[0]) >= 0 and (dest_point[1] - orig_point[1]) * (orig_point[1] - super_point[1]) >= 0): dist *= -1 distance = center.distance(super_point_p) if distance > circle.radius + EPS: return [] val = circle.radius**2 - distance**2 if val < 0: val = 0 front_side = math.sqrt(val) intersections = [] for i in range(-1, 2, 2): if i == 1 and front_side < EPS: break new_dist = dist + front_side * i if new_dist < -EPS or new_dist > segment.length + EPS: continue intersection_point = segment.interpolate(new_dist) intersections.append([intersection_point.x, intersection_point.y]) return intersections
def CircleLineSegmentIntersections(circle, segment): center = Point(circle.center[0], circle.center[1]) distance = segment.distance(center) if distance > circle.radius + EPS: return [] super_point = ShortestToLine(segment, circle.center) super_point_p = Point(super_point[0], super_point[1]) orig_point = segment.coords[0] dest_point = segment.coords[1] dist = Point(orig_point[0], orig_point[1]).distance(super_point_p) if ((dest_point[0] - orig_point[0]) * (orig_point[0] - super_point[0]) >= 0 and (dest_point[1] - orig_point[1]) * (orig_point[1] - super_point[1]) >= 0): dist *= -1 distance = center.distance(super_point_p) if distance > circle.radius + EPS: return [] val = circle.radius**2 - distance**2 if val < 0: val = 0 front_side = math.sqrt(val) intersections = [] for i in range(-1, 2, 2): if i == 1 and front_side < EPS: break new_dist = dist + front_side * i if new_dist < -EPS or new_dist > segment.length + EPS: continue intersection_point = segment.interpolate(new_dist) intersections.append([intersection_point.x, intersection_point.y]) return intersections
def main(): spatialReference = osr.SpatialReference() spatialReference.ImportFromProj4( '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs') driver = ogr.GetDriverByName("ESRI Shapefile") shp_dir = "praries_basins" shutil.rmtree(shp_dir) shapeData = driver.CreateDataSource(shp_dir) layer = shapeData.CreateLayer('layer1', spatialReference, ogr.wkbPolygon) #assert isinstance(layer, Layer) layer.CreateField(ogr.FieldDefn("BasinId")) layerDefinition = layer.GetLayerDefn() input_path = "data/praries_basins/Boundaries_lat_lon.txt" lines = open(input_path).readlines() lons2d = polar_stereographic.lons lats2d = polar_stereographic.lats id_to_points = {} anomaly_i = 1 point_prev = None for line in lines: if line.strip() == "": continue fields = line.split() the_id = fields[0] lon = float(fields[1]) lat = float(fields[2]) if the_id not in id_to_points: id_to_points[the_id] = [] if int(the_id) >= 16: the_point = Point(lon, lat) if point_prev is not None: the_dist = the_point.distance(point_prev) if the_dist > 0.5: id_to_points[ the_id + "_{0}".format(anomaly_i)] = id_to_points[the_id] id_to_points[the_id] = [] anomaly_i += 1 point_prev = the_point id_to_points[the_id].append((lon, lat)) pass polygons = [] featureIndex = 0 for the_id, points in id_to_points.items(): if not len(points): continue feature = ogr.Feature(layerDefinition) feature.SetField("BasinId", the_id) #create a polygon using shapely p = Polygon(shell=points) #print p.wkt polygons.append(p) pGdal = ogr.CreateGeometryFromWkb(p.wkb) feature.SetGeometry(pGdal) feature.SetFID(featureIndex) layer.CreateFeature(feature) featureIndex += 1 shapeData.Destroy() pass
def get_flow_cells(flowline1, flowline2, offset): flowcells = [] centerx = [] centery = [] widths = [] thisdist = 0 thisind1 = 0 thisind2 = 0 maxdist = min(flowline1.length, flowline2.length) gatex = [(flowline1.x[0] + flowline2.x[0]) / 2] gatey = [(flowline1.y[0] + flowline2.y[0]) / 2] lastpt1 = Point(flowline1.coords[0]) lastpt2 = Point(flowline2.coords[0]) widths.append(lastpt1.distance(lastpt2)) while thisdist < maxdist: thispt1 = flowline1.interpolate(thisdist + widths[-1]) # now, get the perp to flow at this point nextind1 = np.searchsorted(flowline1.linedist, thisdist + widths[-1]) if nextind1 == 0: flowvect = np.array(flowline1.coords[1]) - np.array( flowline1.coords[0]) elif nextind1 == len(flowline1.x): break else: flowvect = np.array(flowline1.coords[nextind1]) - np.array( flowline1.coords[nextind1 - 1]) perp = norm_vector(flowvect) f2dist = thispt1.distance(flowline2) flowperp = LineString([(thispt1.x - perp[0] * 1.5 * f2dist, thispt1.y - perp[1] * 1.5 * f2dist), (thispt1.x + perp[0] * 1.5 * f2dist, thispt1.y + perp[1] * 1.5 * f2dist)]) thispt2 = flowline2.intersection(flowperp) if not flowline2.intersects(flowperp): break nextind2 = np.searchsorted(flowline2.linedist, flowline2.project(thispt2)) # there might be a less convoluted way to do this... f1x = np.concatenate([ np.asarray([lastpt1.x]), flowline1.x[thisind1:nextind1], np.asarray([thispt1.x]) ]) f1y = np.concatenate([ np.asarray([lastpt1.y]), flowline1.y[thisind1:nextind1], np.asarray([thispt1.y]) ]) f2x = np.concatenate([ np.asarray([lastpt2.x]), flowline2.x[thisind2:nextind2], np.asarray([thispt2.x]) ]) f2y = np.concatenate([ np.asarray([lastpt2.y]), flowline2.y[thisind2:nextind2], np.asarray([thispt2.y]) ]) flow1coords = list(zip(f1x, f1y)) flow2coords = list(zip(f2x, f2y)) newcell = Cell(flow1coords, flow2coords) flowcells.append(newcell) centerx.append(newcell.x) centery.append(newcell.y) gatex.append(newcell.x_dn) gatey.append(newcell.y_dn) thisind1 = nextind1 thisind2 = nextind2 lastpt1 = thispt1 lastpt2 = thispt2 widths.append(lastpt1.distance(lastpt2)) thisdist += offset return flowcells, widths, (centerx, centery), (gatex, gatey)
def main(): spatialReference = osr.SpatialReference() spatialReference.ImportFromProj4('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs') driver = ogr.GetDriverByName("ESRI Shapefile") shp_dir = "praries_basins" shutil.rmtree(shp_dir) shapeData = driver.CreateDataSource(shp_dir) layer = shapeData.CreateLayer('layer1', spatialReference, ogr.wkbPolygon) #assert isinstance(layer, Layer) layer.CreateField(ogr.FieldDefn("BasinId")) layerDefinition = layer.GetLayerDefn() input_path = "data/praries_basins/Boundaries_lat_lon.txt" lines = open(input_path).readlines() lons2d = polar_stereographic.lons lats2d = polar_stereographic.lats id_to_points = {} anomaly_i = 1 point_prev = None for line in lines: if line.strip() == "": continue fields = line.split() the_id = fields[0] lon = float(fields[1]) lat = float(fields[2]) if the_id not in id_to_points: id_to_points[the_id] = [] if int(the_id) >= 16: the_point = Point(lon, lat) if point_prev is not None: the_dist = the_point.distance(point_prev) if the_dist > 0.5: id_to_points[the_id + "_{0}".format(anomaly_i)] = id_to_points[the_id] id_to_points[the_id] = [] anomaly_i += 1 point_prev = the_point id_to_points[the_id].append((lon, lat)) pass polygons = [] featureIndex = 0 for the_id, points in id_to_points.items(): if not len(points): continue feature = ogr.Feature(layerDefinition) feature.SetField("BasinId", the_id) #create a polygon using shapely p = Polygon(shell=points) #print p.wkt polygons.append(p) pGdal = ogr.CreateGeometryFromWkb(p.wkb) feature.SetGeometry(pGdal) feature.SetFID(featureIndex) layer.CreateFeature(feature) featureIndex += 1 shapeData.Destroy() pass