def part_to_coor(self, particle, last=False): pc_proj = ccrs.PlateCarree() p_dist = particle.coordinates p_dist = [p_dist[:, 0] + self.origin[0], p_dist[:, 1] + self.origin[1]] if last: p_coor = pc_proj.transform_points(ccrs.UTM(zone=10), np.array((p_dist[:, -1])), np.array((p_dist[:, -1]))) else: p_coor = pc_proj.transform_points(ccrs.UTM(zone=10), np.array([p_dist[:, 0]]), np.array([p_dist[:, 1]])) p_coor = p_coor[:, :2] return p_coor
def plot_raster(self, band, factor=1, writefile=False, filename='rgb.pdf', **kwargs): crs = ccrs.UTM('18N') av_dates = self._obj.coords['time'].data.tolist() # Set plot dimensions plt.figure(figsize=(15, 3 * math.ceil(len(av_dates) / 5.0))) # Plot every date for ix, date in enumerate(av_dates): if factor is not 1: da = self._obj.sel(time=date)[band] * factor else: da = self._obj.sel(time=date)[band] #ap = rgb.isel(time=ix)*factor ax = plt.subplot(math.ceil(len(av_dates) / 5.0), 5, 1 + ix, projection=crs) #ap.plot.imshow(rgb='band', transform=crs) plt.imshow(da.data, **kwargs) # Write plot if writefile: plt.savefig(filename, dpi=300) plt.show()
def scale_bar(ax, lat, lon, length, location=(0.5, 0.05), linewidth=5): """ ax is the axes to draw the scalebar on. location is center of the scalebar in axis coordinates ie. 0.5 is the middle of the plot length is the length of the scalebar in km. linewidth is the thickness of the scalebar. """ import utm import cartopy.crs as ccrs #Projection in metres, need to change this to suit your own figure zone = utm.latlon_to_zone_number(lat,lon) if lat < 0: sh = True else: sh = False utm_c = ccrs.UTM(zone, southern_hemisphere=sh) #Get the extent of the plotted area in coordinates in metres x0, x1, y0, y1 = ax.get_extent(utm_c) #Turn the specified scalebar location into coordinates in metres sbcx, sbcy = x0 + (x1 - x0) * location[0], y0 + (y1 - y0) * location[1] #Generate the x coordinate for the ends of the scalebar for i in range(0,length): if i % 2 == 0: c = 'k' else: c = 'w' bar_xs = [sbcx - length * 500 + i * 1000, sbcx - length * 500 + (i+1) * 1000] #Plot the scalebar ax.plot(bar_xs, [sbcy, sbcy], transform=utm_c, color=c, linewidth=linewidth) #Plot the scalebar label sbcy = sbcy + (y1 - y0) * 0.02 ax.text(sbcx, sbcy, str(length) + ' km', color="black", transform=utm_c, fontweight="bold", horizontalalignment='center', verticalalignment='bottom', fontsize=15)
def scale_bar(ax, proj, length, location=(0.5, 0.05), linewidth=3, units='km', m_per_unit=1000, UTM=18): """ http://stackoverflow.com/a/35705477/1072212 ax is the axes to draw the scalebar on. proj is the projection the axes are in location is center of the scalebar in axis coordinates ie. 0.5 is the middle of the plot length is the length of the scalebar in km. linewidth is the thickness of the scalebar. units is the name of the unit m_per_unit is the number of meters in a unit """ # find lat/lon center to find best UTM zone x0, x1, y0, y1 = ax.get_extent(proj.as_geodetic()) # Projection in metres utm = ccrs.UTM(UTM) # Get the extent of the plotted area in coordinates in metres x0, x1, y0, y1 = ax.get_extent(utm) # Turn the specified scalebar location into coordinates in metres sbcx, sbcy = x0 + (x1 - x0) * location[0], y0 + (y1 - y0) * location[1] # Generate the x coordinate for the ends of the scalebar bar_xs = [sbcx - length * m_per_unit / 2, sbcx + length * m_per_unit / 2] # buffer for scalebar buffer = [patheffects.withStroke(linewidth=5, foreground="w")] # Plot the scalebar with buffer ax.plot(bar_xs, [sbcy, sbcy], transform=utm, color='k', linewidth=linewidth, path_effects=None) # buffer for text buffer = [patheffects.withStroke(linewidth=3, foreground="w")] # Plot the scalebar label t0 = ax.text(sbcx, sbcy, str(length) + ' ' + units, transform=utm, horizontalalignment='center', verticalalignment='bottom', path_effects=None, zorder=2) left = x0 + (x1 - x0) * 0.05 # Plot the N arrow # t1 = ax.text(left, sbcy, u'\u25B2\nN', transform=utm, # horizontalalignment='center', verticalalignment='bottom', # path_effects=buffer, zorder=2) # Plot the scalebar without buffer, in case covered by text buffer ax.plot(bar_xs, [sbcy, sbcy], transform=utm, color='k', linewidth=linewidth, zorder=3)
def get_ants_installed_since(self, query_date, station_types_to_check='all'): """ Get list of antennas installed since query_date. Parameters ---------- query_date : astropy Time Date to get limit check for installation. station_types_to_check : str or list of str Stations types to limit check. """ import cartopy.crs as ccrs station_types_to_check = self.parse_station_types_to_check( station_types_to_check) dt = query_date.gps latlon_p = ccrs.Geodetic() utm_p = ccrs.UTM(self.hera_zone[0]) lat_corr = self.lat_corr[self.hera_zone[1]] found_stations = [] for a in self.session.query(geo_location.GeoLocation).filter( geo_location.GeoLocation.created_gpstime >= dt): if a.station_type_name.lower() in station_types_to_check: a.gps2Time() a.desc = self.station_types[a.station_type_name]['Description'] a.lon, a.lat = latlon_p.transform_point( a.easting, a.northing - lat_corr, utm_p) a.X, a.Y, a.Z = uvutils.XYZ_from_LatLonAlt( radians(a.lat), radians(a.lon), a.elevation) found_stations.append(copy.copy(a)) if self.fp_out is not None and not self.testing: # pragma: no cover self.fp_out.write('{}\n'.format(self._loc_line(a))) return found_stations
def main(): # Create a list of integers from 1 - 60 zones = range(1, 61) # Create a figure fig = plt.figure(figsize=(18, 6)) # Loop through each zone in the list for zone in zones: # Add GeoAxes object with specific UTM zone projection to the figure ax = fig.add_subplot(1, len(zones), zone, projection=ccrs.UTM(zone=zone, southern_hemisphere=True)) # Add coastlines, gridlines and zone number for the subplot ax.coastlines(resolution='110m') ax.gridlines() ax.set_title(zone) # Add a supertitle for the figure fig.suptitle("UTM Projection - Zones") # Display the figure plt.show()
def request_basemap_tiles( lon, lat, dx, dy, url='https://mt1.google.com/vt/lyrs=s&x={X}&y={Y}&z={Z}', utm=False): if utm == False: extents = (lon - dx, lat - dy, lon + dx, lat + dy) tiles = gv.WMTS(url, extents=extents) location = gv.Points([], vdims="vertices") point_stream = PointDraw(source=location) tiles = gv.WMTS(url, extents=extents) return tiles else: u = utm.from_latlon(lat, lon) utm_lon = u[0] utm_lat = u[1] utm_zone = u[2] utm_zone_code = u[3] extents = utm_lon - dx, utm_lat - dy, utm_lon + dx, utm_lat + dy tiles = gv.WMTS(url, extents=extents, crs=ccrs.UTM(utm_zone)) return tiles, utm_zone
def test_default(south): zone = 1 # Limits are fixed, so don't bother checking other zones. utm = ccrs.UTM(zone, southern_hemisphere=south) other_args = {'ellps=WGS84', 'units=m', 'zone={}'.format(zone)} if south: other_args |= {'south'} check_proj_params('utm', utm, other_args) assert_almost_equal(np.array(utm.x_limits), [-250000, 1250000]) assert_almost_equal(np.array(utm.y_limits), [-10000000, 25000000])
def test_utm(self): utm30n = ccrs.UTM(30) ll = ccrs.Geodetic() lat, lon = np.array([51.5, -3.0], dtype=np.double) east, north = np.array([500000, 5705429.2], dtype=np.double) assert_arr_almost_eq(utm30n.transform_point(lon, lat, ll), [east, north], decimal=1) assert_arr_almost_eq(ll.transform_point(east, north, utm30n), [lon, lat], decimal=1) utm38s = ccrs.UTM(38, southern_hemisphere=True) lat, lon = np.array([-18.92, 47.5], dtype=np.double) east, north = np.array([763316.7, 7906160.8], dtype=np.double) assert_arr_almost_eq(utm38s.transform_point(lon, lat, ll), [east, north], decimal=1) assert_arr_almost_eq(ll.transform_point(east, north, utm38s), [lon, lat], decimal=1)
def read(self, path, project_name='*', crs=ccrs.UTM(1), fmt='nc'): file_path = Path(path) if not file_path.is_file(): file_path = file_path / f'{project_name}.{fmt}' if fmt == 'nc': xarr = xr.open_dataset(file_path) elif fmt == '2dm' or fmt == '3dm': mesh_path = os.path.join(file_path) xarr = parse_mesh_file(mesh_path, crs=crs) return self.from_xarray(xarr, crs=crs)
def viz2d(ds, r_band='red', g_band='green', b_band='blue'): """ Visualize the first time step of the dataset. Description ---------- Visualize the first time step using specific spectral bands available in the dataset. Parameters ---------- dataset: xr.Dataset A multi-dimensional array with x,y and time dimensions and one or more data variables. r: string Name of the data variable in string. This will be input in the red channel. g: string Name of the data variable in string. This will be input in the green channel. b: string Name of the data variable in string. This will be input in the blue channel. Returns ------- mesh: matplotlib.collections.QuadMesh A two dimensional plot in RGB color, either true or false color composites. """ try: da_rgb = ds.isel(time=0).to_array().rename({ "variable": "band" }).sel(band=[r_band, g_band, b_band]) except NameError as error: print('Dataset is not defined.') except AttributeError as error: print('Input data need to be a xarray dataset.') except KeyError: print('The band(s) cannot be found.') #set projection to pre-defined CRS; CRS can be checked using `aoi.crs` ax = plt.subplot(projection=ccrs.UTM('33S')) plot = da_rgb.plot.imshow(ax=ax, rgb='band', transform=ccrs.UTM('33S'), robust=True) return plot
def seed_particles(self, center_coord, radius): ''' Create a of cluster of particles within a radius in (km)''' x_pos, y_pos = ccrs.UTM(zone=10).transform_point( center_coord[0], center_coord[1], ccrs.PlateCarree()) col_num = [1, 3, 5, 3, 1] dx = radius / 4 * 1000 ylevel = (np.arange(max(col_num)) - 3) * dx for i, n in enumerate(col_num): x = np.arange(n) x = x - (n - 1) / 2 x = x * dx y = np.ones(shape=x.shape) * ylevel[i] pos_x = x_pos + x pos_y = y_pos + y coors = ccrs.PlateCarree().transform_points( ccrs.UTM(zone=10), pos_x, pos_y) x_coors = coors[:, 0] y_coors = coors[:, 1] for pos in zip(x_coors, y_coors): self.add_particle(pos)
def utm_plot(): import matplotlib.pyplot as plt import cartopy.crs as ccrs nplots = 60 fig = plt.figure(figsize=(10, 3)) for i in range(0, nplots): ax = fig.add_subplot(1, nplots, i+1, projection=ccrs.UTM(zone=i+1, southern_hemisphere=True)) ax.coastlines(resolution='110m') ax.gridlines()
def pick_points_from_basemap_tiles(tiles, utm_zone=None): if utm_zone == None: location = gv.Points([], vdims="vertices") else: location = gv.Points([], vdims="vertices", crs=ccrs.UTM(utm_zone)) point_stream = PointDraw(source=location) base_map = (tiles * location).opts( opts.Points(width=500, height=500, size=12, color='black', tools=["hover"])) app = pn.panel(base_map) return app, point_stream
def __init__(self): self.minlon, self.maxlon, self.minlat, self.maxlat, self.resolution_km, self.url, self.days_to_capture, self.start_time = self.set_model_parameters( default=True) self.current_dataset = self._get_HFR_subset() self.lat = self.current_dataset['lat'].values self.lon = self.current_dataset['lon'].values self.x = np.arange(0, len(self.lon), 1) * 1850 self.y = np.arange(0, len(self.lat), 1) * 1995 self.x_grid, self.y_grid = np.meshgrid(self.x, self.y) self.lon_grid, self.lat_grid = np.meshgrid(self.lon, self.lat) self.origin = ccrs.UTM(zone=10).transform_point( self.lon[0], self.lat[0], ccrs.PlateCarree()) self.time_index = 0 self.hours_elapsed = 0 self.current_time = self.start_time self.particles = np.array([]) self.time_step = .25
def get_crs(self): if self.crs_label == 'UTM': if self.UTM_zone_hemi == 'South': hemi = True else: hemi = False proj = ccrs.UTM(self.UTM_zone_num, southern_hemisphere=hemi) elif self.crs_label == 'Geographic': proj = ccrs.PlateCarree() elif self.crs_label == 'Mercator': proj = ccrs.GOOGLE_MERCATOR else: raise RuntimeError('Projection not found.') return proj
def test_ellipsoid_transform(): # USGS Professional Paper 1395, pp 269 - 271 globe = ccrs.Globe(ellipse='clrk66') utm = ccrs.UTM(zone=18, globe=globe) geodetic = utm.as_geodetic() other_args = {'ellps=clrk66', 'units=m', 'zone=18'} check_proj_params('utm', utm, other_args) assert_almost_equal(np.array(utm.x_limits), [-250000, 1250000]) assert_almost_equal(np.array(utm.y_limits), [-10000000, 25000000]) result = utm.transform_point(-73.5, 40.5, geodetic) assert_almost_equal(result, np.array([127106.5 + 500000, 4484124.4]), decimal=1) inverse_result = geodetic.transform_point(result[0], result[1], utm) assert_almost_equal(inverse_result, [-73.5, 40.5])
def from_xarray(self, xarr, crs=ccrs.UTM(1)): self.name = xarr.nodes.attrs.get('MESHNAME').strip('\'').strip('"') self.verts = xarr.nodes.to_pandas() # store as one-based self.tris = xarr.E3T.to_pandas() - 1 # store as zero-based (will be paired with mesh_points which uses zero-based indices) # TODO: why don't we just store the mesh as a xarray instead of pandas? file_crs = get_crs(xarr) if crs: if crs.proj4_params != file_crs.proj4_params: log.warning('Specified crs ({}) does not match file ({}). Defaulting to file crs'.format( crs.proj4_params, file_crs.proj4_params)) self.projection.set_crs(file_crs) else: self.projection.set_crs(crs) else: self.projection.set_crs(file_crs) self.reproject_points() self.tri_mesh = gv.TriMesh((self.tris[['v0', 'v1', 'v2']], self.mesh_points))
def get_location(self, to_find_list, query_date): """ Get GeoLocation objects for a list of station_names. Parameters ---------- to_find_list : list of str station names to find query_date : string, int, Time, datetime Date to get information for, anything that can be parsed by `get_astropytime`. Returns ------- list of GeoLocation objects GeoLocation objects corresponding to station names. """ import cartopy.crs as ccrs latlon_p = ccrs.Geodetic() utm_p = ccrs.UTM(self.hera_zone[0]) lat_corr = self.lat_corr[self.hera_zone[1]] locations = [] self.query_date = cm_utils.get_astropytime(query_date) for station_name in to_find_list: for a in self.session.query(geo_location.GeoLocation).filter( (func.upper(geo_location.GeoLocation.station_name) == station_name.upper()) & (geo_location.GeoLocation.created_gpstime < self.query_date.gps)): a.gps2Time() a.desc = self.station_types[a.station_type_name]['Description'] a.lon, a.lat = latlon_p.transform_point( a.easting, a.northing - lat_corr, utm_p) a.X, a.Y, a.Z = uvutils.XYZ_from_LatLonAlt( radians(a.lat), radians(a.lon), a.elevation) locations.append(copy.copy(a)) if self.fp_out is not None and not self.testing: # pragma: no cover self.fp_out.write('{}\n'.format(self._loc_line(a))) return locations
def plot_RGB(self, bands=['red', 'green', 'blue'], factor=0.0001, writefile=False, filename='rgb.pdf'): crs = ccrs.UTM('18N') av_dates = self._obj.coords['time'].data.tolist() # Set plot dimensions plt.figure(figsize=(15, 3 * math.ceil(len(av_dates) / 5.0))) # Try to create the rgb xarray try: arrays = [] for band in bands: arrays.append(self._obj[band]) rgb = xr.concat(arrays, pd.Index(bands, name='band')).sortby('time') rgb.name = 'rgb' except: print('The EOTempArray does not contain rgb bands') return None # Plot every date for ix, date in enumerate(av_dates): ap = rgb.isel(time=ix) * factor ax = plt.subplot(math.ceil(len(av_dates) / 5.0), 5, 1 + ix, projection=crs) ap.plot.imshow(rgb='band', transform=crs) # Write plot if writefile: plt.savefig(filename, dpi=300) plt.show()
def UTM2latlon(easting,northing,zone,south=False): """ Calculate latitude/longitude from UTM. Parameters: easting: UTM easting (m) northing: UTM northing (m) zone: UTM zone as integer south: Whether UTM zone is from the southern hemisphere Returns: lat: Latitude (decimal degrees) lon: Longitude (decimal degrees) """ # Set ouptput to lat/lon crs = ccrs.Geodetic() # Convert lon,lat = crs.transform_point( easting,northing,src_crs=ccrs.UTM(zone=zone, southern_hemisphere=south)) return(lat,lon)
def read_maloof_dem(filename): # Open file using GDAL read only(!) raster = gdal.Open(filename, gdal.GA_ReadOnly) # Read the data from the raster data = raster.ReadAsArray() # Dimensions dimx = raster.RasterXSize dimy = raster.RasterYSize # Number of bands nbands = raster.RasterCount # Metadata for the raster dataset meta = raster.GetMetadata() # Get extemt from file gt = raster.GetGeoTransform() extent = (gt[0], gt[0] + raster.RasterXSize * gt[1], gt[3] + raster.RasterYSize * gt[5], gt[3]) # Get UTM zone from extent utmzone = int(np.round(((180+np.mean(extent[:2]))/6))) + 2 print(utmzone) # Get UTM projection from projection = ccrs.UTM(utmzone) # Get Platitude and longitude vectors lat = np.linspace(*(extent[2:]), data.shape[0]) lon = np.linspace(*(extent[:2]), data.shape[1]) # Get geo transform/extent for plotting return lat, lon, data, projection, extent
counties = shpreader.Reader(shp_name) counties = counties.records() country = next(counties) # ============================================================================= # df_table = pd.read_csv(r'E:\Research\Benmap\output/df_table.csv').drop('Unnamed: 0',axis=1) # ============================================================================= df_table = pd.read_csv( r'E:\Research\Benmap\output/df_table_inclusive.csv').drop('Unnamed: 0', axis=1) # ============================================================================= # plot # ============================================================================= data_crs = ccrs.AlbersEqualArea() useproj = ccrs.UTM(10) # ============================================================================= # projections = [ccrs.PlateCarree(), # PlateCarree somehow works now.......................... # ccrs.AlbersEqualArea() # ,ccrs.AzimuthalEquidistant() # ,ccrs.EquidistantConic() # ,ccrs.LambertConformal() # ,ccrs.LambertCylindrical() # ,ccrs.Mercator() # ,ccrs.Miller() # ,ccrs.Mollweide() # ,ccrs.Orthographic() # ,ccrs.Robinson() # ,ccrs.Sinusoidal() # ,ccrs.Stereographic()
# Copyright (c) 2018, Julien Seguinot (juseg.github.io) # GNU General Public License v3.0+ (https://www.gnu.org/licenses/gpl-3.0.txt) """ Plot Hokkaido topographic map. """ import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartowik.naturalearth as cne import cartowik.shadedrelief as csr # initialize figure fig = plt.figure() ax = fig.add_axes([0.0, 0.0, 1.0, 1.0], projection=ccrs.UTM(54)) ax.set_extent((250e3, 1050e3, 4500e3, 5100e3), crs=ax.projection) # add relief maps csr.add_bathymetry('external/cleantopo2.tif', offset=10701.0) csr.add_multishade('external/cleantopo2.tif') csr.add_topography('external/srtm.tif', vmax=4500) csr.add_multishade('external/srtm.tif') # add physical elements cne.add_rivers(ax=ax) cne.add_lakes(ax=ax) cne.add_coastline(ax=ax) # add cultural elements cne.add_states(ax=ax, facecolor='w', alpha=0.5,
from rasterio.features import rasterize mask = rasterize([poly], transform=src.transform, out_shape=src.shape) # Rasterio and Cartopy """ Plot a raster image with Cartopy axes Kelsey Jordahl SciPy tutorial 2015 """ import os import rasterio import cartopy.crs as ccrs import matplotlib.pyplot as plt utm18n = ccrs.UTM(18) ax = plt.axes(projection=utm18n) plt.title('UTM zone 18N') here = os.path.dirname(os.path.abspath('__file__')) data_dir = os.path.join(here, '..', 'data') raster_file = os.path.join(data_dir, 'manhattan.tif') with rasterio.open(raster_file) as src: left, bottom, right, top = src.bounds ax.imshow(src.read(1), origin='upper', extent=(left, right, bottom, top), cmap='gray') x = [left, right, right, left, left] y = [bottom, bottom, top, top, bottom]
""" Surface contours ================ Plot a composite map including bedrock altitude, a half-transparent ice mask, a surface altitude contour, and geographic elements. """ import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.feature as cfeature import xarray as xr import hyoga.demo # initialize figure ax = plt.subplot(projection=ccrs.UTM(32)) # open demo data with xr.open_dataset(hyoga.demo.get('pism.alps.out.2d.nc')) as ds: ds = ds.hyoga.where_thicker(1) # plot model output ds.hyoga.plot.bedrock_altitude(ax=ax, vmin=0, vmax=3000) ds.hyoga.plot.ice_margin(ax=ax, facecolor='w') ds.hyoga.plot.surface_altitude_contours(ax=ax, colors='tab:blue') # add coastlines and rivers ax.coastlines(edgecolor='0.25', linewidth=0.5) ax.add_feature( cfeature.NaturalEarthFeature( category='physical', name='rivers_lake_centerlines', scale='10m'),
# next, we transpose the image to re-order the indices dispimg = dispimg.transpose([1, 2, 0]) # finally, we display the image handle = ax.imshow(dispimg[:, :, bands], **imshow_args) return handle, ax # ------------------------------------------------------------------------ with rio.open('data_files/NI_Mosaic.tif') as dataset: img = dataset.read() xmin, ymin, xmax, ymax = dataset.bounds myCRS = ccrs.UTM(29) # make a new figure and axis with a UTM29 N CRS fig, ax = plt.subplots(1, 1, figsize=(10, 10), subplot_kw=dict(projection=myCRS)) # draw the gridlines on the axis (copied from Week 2) gridlines = ax.gridlines(draw_labels=True, xlocs=[-8, -7.5, -7, -6.5, -6, -5.5], ylocs=[54, 54.5, 55, 55.5]) gridlines.right_labels = False gridlines.bottom_labels = False # create a kwargs dict to use for the image display my_kwargs = {'extent': [xmin, xmax, ymin, ymax], 'transform': myCRS}
plt.text(sbx - 12500, sby - 4500, '10 km', transform=tmc, fontsize=8) plt.text(sbx - 24500, sby - 4500, '0 km', transform=tmc, fontsize=8) # load the datasets outline = gpd.read_file('data_files/NI_outline.shp') towns = gpd.read_file('data_files/Towns.shp') water = gpd.read_file('data_files/Water.shp') rivers = gpd.read_file('data_files/Rivers.shp') counties = gpd.read_file('data_files/Counties.shp') # create a figure of size 10x10 (representing the page size in inches) myFig = plt.figure(figsize=(10, 10)) myCRS = ccrs.UTM( 29 ) # create a Universal Transverse Mercator reference system to transform our data. ax = plt.axes(projection=ccrs.Mercator( )) # finally, create an axes object in the figure, using a Mercator # projection, where we can actually plot our data. # first, we just add the outline of Northern Ireland using cartopy's ShapelyFeature outline_feature = ShapelyFeature(outline['geometry'], myCRS, edgecolor='k', facecolor='w') xmin, ymin, xmax, ymax = outline.total_bounds ax.add_feature(outline_feature) # add the features we've created to the map.
import matplotlib import matplotlib.pyplot as plt import numpy as np from osgeo import ogr import matplotlib.pyplot as plt import rasterio import cartopy.crs as ccrs import geopandas from geopandas import * MediumApple = (85.00, 255.00, 0.00) Cantaloupe = (255.00, 167.00, 127.00) Marsred = (255.00, 0.00, 0.00) crs = ccrs.UTM(zone=10) ax = plt.axes(projection=crs) CAcountylist = [ "ala", "alp", "ama", "bte", "cal", "cco", "col", "del", "eld", "fre", "gln", "hmb", "imp", "iny", "kng", "krn", "lag", "lak", "las", "mad", "mar", "men", "mer", "mnt", "mod", "mon", "mrp", "nap", "nev", "org", "pla", "plu", "riv", "sac", "sbb", "sbn", "sbr", "scl", "sdg", "sfr", "sha", "sir", "sis", "sjq", "slo", "smt", "snc", "sol", "son", "sta", "sut", "teh", "tlm", "trn", "tul", "ven", "yol", "yub" ] ABcountylist = [ "a10", "a11", "a12", "a13", "a14", "a15", "a16", "a17", "a18", "a19", "a20", "a21", "a22", "a23", "ab1", "ab2", "ab3", "ab4", "ab5", "ab6", "ab7", "ab8", "ab9" ]
with open(os.path.join(entity_dir, file), 'wb') as output: shutil.copyfileobj(response.raw, output) del response #Read the rasters using rasterio and extract the bounds. xmin, xmax, ymin, ymax = [], [], [], [] for image_path in glob(os.path.join(LANDSAT_PATH, '*/*B10.TIF')): with rasterio.open(image_path) as src_raster: xmin.append(src_raster.bounds.left) xmax.append(src_raster.bounds.right) ymin.append(src_raster.bounds.bottom) ymax.append(src_raster.bounds.top) fig, ax = plt.subplots(1, 1, figsize=(20, 15), subplot_kw={'projection': ccrs.UTM(16)}) ax.set_extent([min(xmin), max(xmax), min(ymin), max(ymax)], ccrs.UTM(16)) bounds.plot(ax=ax, transform=ccrs.PlateCarree()) for image_path in glob(os.path.join(LANDSAT_PATH, '*/*B10.TIF')): with rasterio.open(image_path) as src_raster: extent = [src_raster.bounds[i] for i in [0, 2, 1, 3]] dst_transform = from_origin(src_raster.bounds.left, src_raster.bounds.top, 250, 250) width = np.ceil((src_raster.bounds.right - src_raster.bounds.left) / 250.).astype('uint')