Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
from os.path import isfile, isdir, join
from osgeo import gdal, gdalnumeric, ogr, osr
from skimage import io
gdal.UseExceptions()
io.use_plugin('matplotlib')
##############################################
# MAIN
##############################################
# go to directory
wd = '/home/heiko/linuxpy/test/' # working directory on Linux Virtual Box
os.chdir(wd)
# define a map projection
tifproj = ccrs.epsg(27700)
# EPSG 27700 is the British National Grid
# make the figure and the axes objects
fig, (a0,a1) = plt.subplots(2, 1, figsize=(4,5), gridspec_kw={'height_ratios':[9, 1]}, subplot_kw=dict(projection=tifproj))
a0.set_visible(False)
a1.set_visible(False)
# the above command creates two subplots in different rows, they have axes objects a0 and a1
# the corners below cover roughly the British Isles
left1 = 49000
right1 = 688000
bottom1 = 14000
top1 = 1232000
left2 = left1
right2 = right1
def plot_shapes_one(self, data_gpd, timestamp, crs):
""" Plots shapes for one timestamp from geopandas GeoDataFrame
:param data_gpd: data to plot
:type data_gpd: geopandas.GeoDataFrame
:param timestamp: timestamp to plot data for
:type timestamp: datetime
:param crs: in which crs is the data to plot
:type crs: sentinelhub.crs
:return: visualization
:rtype: geoviews
"""
out = data_gpd.loc[data_gpd[self.timestamp_column] == timestamp]
return gv.Polygons(out, crs=ccrs.epsg(int(crs.value)))
crs_proj4 = crs.proj4_init
df_ae = df.to_crs(crs_proj4)
# Here's what the plot looks like in GeoPandas
df_ae.plot()
###############################################################################
# Now that our data is in a CRS based off of CartoPy, we can easily
# plot it.
fig, ax = plt.subplots(subplot_kw={'projection': crs})
ax.add_geometries(df_ae['geometry'], crs=crs)
###############################################################################
# Note that we could have easily done this with an EPSG code like so:
crs_epsg = ccrs.epsg('3857')
df_epsg = df.to_crs(epsg='3857')
# Generate a figure with two axes, one for CartoPy, one for GeoPandas
fig, axs = plt.subplots(1, 2, subplot_kw={'projection': crs_epsg},
figsize=(10, 5))
# Make the CartoPy plot
axs[0].add_geometries(df_epsg['geometry'], crs=crs_epsg,
facecolor='white', edgecolor='black')
# Make the GeoPandas plot
df_epsg.plot(ax=axs[1], color='white', edgecolor='black')
###############################################################################
# CartoPy to GeoPandas
# ====================
#
# Next we'll perform a CRS projection in CartoPy, and then convert it
cmap = 'RdBu_r'
else:
cmap = 'viridis'
if show_grid_lines :
gl = ax.gridlines(crs=ccrs.PlateCarree(),
linewidth=1, color='black',
draw_labels = show_grid_labels,
alpha=0.5, linestyle='--', zorder=102)
else:
gl = []
if data_projection_code == 4326: # lat lon does nneed to be projected
data_crs = ccrs.PlateCarree()
else:
data_crs =ccrs.epsg(data_projection_code)
if custom_background:
ax.background_img(name=background_name, resolution=background_resolution)
if plot_type == 'pcolormesh':
p = ax.pcolormesh(xx, yy, data, transform=data_crs,
vmin=cmin, vmax=cmax, cmap=cmap)
elif plot_type =='contourf':
p = ax.contourf(xx, yy, data, levels, transform=data_crs,
vmin=cmin, vmax=cmax, cmap=cmap)
else:
raise ValueError('plot_type must be either "pcolormesh" or "contourf"')
if not custom_background:
ax.add_feature(cfeature.LAND, zorder=100)
try:
import cartopy.crs as ccrs
import geoviews as gv # noqa
except:
raise ImportError('Geographic projection support requires GeoViews and cartopy.')
if crs is None:
return ccrs.PlateCarree()
if isinstance(crs, basestring) and crs.lower().startswith('epsg'):
try:
crs = ccrs.epsg(crs[5:].lstrip().rstrip())
except:
raise ValueError("Could not parse EPSG code as CRS, must be of the format 'EPSG: {code}.'")
elif isinstance(crs, int):
crs = ccrs.epsg(crs)
elif isinstance(crs, basestring) or is_pyproj(crs):
try:
crs = proj_to_cartopy(crs)
except:
raise ValueError("Could not parse EPSG code as CRS, must be of the format 'proj4: {proj4 string}.'")
elif not isinstance(crs, ccrs.CRS):
raise ValueError("Projection must be defined as a EPSG code, proj4 string, cartopy CRS or pyproj.Proj.")
return crs
def get_ccrs(filename):
"""
Loads WKT projection string from file and return
cartopy coordinate reference system.
"""
inproj = osr.SpatialReference()
proj = open(filename, 'r').readline()
inproj.ImportFromWkt(proj)
projcs = inproj.GetAuthorityCode('PROJCS')
return ccrs.epsg(projcs)
""" Plots the FeatureType.DATA of eopatch.
:param feature_name: name of the eopatch feature
:type feature_name: str
:return: visualization
:rtype: holoview/geoviews/bokeh
"""
crs = self.eopatch.bbox.crs
crs = CRS.POP_WEB if crs is CRS.WGS84 else crs
data_da = array_to_dataframe(self.eopatch, (FeatureType.DATA, feature_name), crs=crs)
if self.mask:
data_da = self.mask_data(data_da)
timestamps = self.eopatch.timestamp
crs = self.eopatch.bbox.crs
if not self.rgb:
return data_da.hvplot(x='x', y='y', crs=ccrs.epsg(int(crs.value)))
data_rgb = self.eopatch_da_to_rgb(data_da, feature_name, crs)
rgb_dict = {timestamp_: self.plot_rgb_one(data_rgb, timestamp_) for timestamp_ in timestamps}
return hv.HoloMap(rgb_dict, kdims=['time'])
:type feature_type: FeatureType
:param feature_name: name of eopatch feature
:type feature_name: str
:return: visualization
:rtype: holoviews/geoviews/bokeh
"""
crs = self.eopatch.bbox.crs
crs = CRS.POP_WEB if crs is CRS.WGS84 else crs
data_da = array_to_dataframe(self.eopatch, (feature_type, feature_name), crs=crs)
data_min = data_da.values.min()
data_max = data_da.values.max()
data_levels = len(np.unique(data_da))
data_levels = 11 if data_levels > 11 else data_levels
data_da = data_da.where(data_da > 0).fillna(-1)
vis = data_da.hvplot(x='x', y='y',
crs=ccrs.epsg(int(crs.value))).opts(clim=(data_min, data_max),
clipping_colors={'min': 'transparent'},
color_levels=data_levels)
return vis
3. cartopy.crs.CRS instance
4. None defaults to crs.PlateCaree
"""
try:
import cartopy.crs as ccrs
import geoviews as gv # noqa
import pyproj
except:
raise ImportError('Geographic projection support requires GeoViews and cartopy.')
if crs is None:
return ccrs.PlateCarree()
if isinstance(crs, basestring) and crs.lower().startswith('epsg'):
try:
crs = ccrs.epsg(crs[5:].lstrip().rstrip())
except:
raise ValueError("Could not parse EPSG code as CRS, must be of the format 'EPSG: {code}.'")
elif isinstance(crs, int):
crs = ccrs.epsg(crs)
elif isinstance(crs, (basestring, pyproj.Proj)):
try:
crs = proj_to_cartopy(crs)
except:
raise ValueError("Could not parse EPSG code as CRS, must be of the format 'proj4: {proj4 string}.'")
elif not isinstance(crs, ccrs.CRS):
raise ValueError("Projection must be defined as a EPSG code, proj4 string, cartopy CRS or pyproj.Proj.")
return crs
#print(projsr)
projwkt = projsr.ExportToWkt()
#print(projwkt)
projosr = osr.SpatialReference()
# convert wkt projection to Cartopy projection
projosr.ImportFromWkt(projwkt)
#print(projosr)
projcs = projosr.GetAuthorityCode('PROJCS')
if projcs == None:
print("No EPSG code found in shapefile. Using EPSG 4326 instead. Make sure the .prj file contains AUTHORITY={CODE}.")
projcs = 4326 # if no EPSG code given, set to geojson default
print(projcs)
if projcs == 4326:
shapeproj = ccrs.PlateCarree()
else:
shapeproj = ccrs.epsg(projcs) # Returns the projection which corresponds to the given EPSG code.
# The EPSG code must correspond to a “projected coordinate system”,
# so EPSG codes such as 4326 (WGS-84) which define a “geodetic
# coordinate system” will not work.
print("\nShapefile projection:")
print(shapeproj)
# make the figure
fig = plt.figure(figsize=(figsizex, figsizey))
# ---------------------- Surrounding frame ----------------------
# set up frame full height, full width of figure, this must be called first
left = -0.01
bottom = -0.01
width = 1.02
height = 1.02
rect = [left, bottom, width, height]