Example #1
0
def test_plotting_extent():
    from rasterio.plot import reshape_as_image
    expected = (101985.0, 339315.0, 2611485.0, 2826915.0)
    with rasterio.open('tests/data/RGB.byte.tif') as src:
        assert plotting_extent(src) == expected
        assert plotting_extent(
            reshape_as_image(src.read()), transform=src.affine) == expected
        assert plotting_extent(
            src.read(1), transform=src.transform) == expected
        # array requires a transform
        with pytest.raises(ValueError):
            plotting_extent(src.read(1))
Example #2
0
def test_plotting_extent():
    from rasterio.plot import reshape_as_image
    expected = (101985.0, 339315.0, 2611485.0, 2826915.0)
    with rasterio.open('tests/data/RGB.byte.tif') as src:
        assert plotting_extent(src) == expected
        assert plotting_extent(
            reshape_as_image(src.read()), transform=src.transform) == expected
        assert plotting_extent(
            src.read(1), transform=src.transform) == expected
        # array requires a transform
        with pytest.raises(ValueError):
            plotting_extent(src.read(1))
Example #3
0
def readingIR_all(ls_path_tif, filetif):
    Piren_IR_ls = []
    Piren_IR_name = []
    mapping_columns = {}
    for path_tif in ls_path_tif:
        IR_src = rio.open(os.path.join(path_tif))
        Piren_IR_array = IR_src.read(1)  # Lit la bande 1
        Piren_Limits = plotting_extent(IR_src)  # Limites
        Piren_res = IR_src.res  # resolution
        Piren_IR_ls.append([Piren_IR_array, Piren_Limits, IR_src])
    Piren_IR_name.append(filetif)
    Piren_IR = pd.DataFrame(np.array(
        [Piren_IR_ls[0][0], Piren_IR_ls[0][1], Piren_IR_ls[0][2]],
        dtype=object).T,
                            index=["IR_array", "Limits", "IR_src"],
                            columns=['IR_' + filetif[0]])
    ## Ajout de plusieurs images IR, A modifier
    Piren_IR = Piren_IR.assign(IR_7H29=Piren_IR_ls[1])
    Piren_IR = Piren_IR.assign(IR_8H22=Piren_IR_ls[2])
    Piren_IR = Piren_IR.assign(IR_9H28=Piren_IR_ls[3])
    Piren_IR = Piren_IR.assign(IR_10H22=Piren_IR_ls[4])
    Piren_IR = Piren_IR.assign(IR_11H27=Piren_IR_ls[5])
    Piren_IR = Piren_IR.assign(IR_12H31=Piren_IR_ls[6])
    Piren_IR = Piren_IR.assign(IR_13H26=Piren_IR_ls[7])
    Piren_IR = Piren_IR.assign(IR_15H59=Piren_IR_ls[8])
    Piren_IR = Piren_IR.assign(IR_17H27=Piren_IR_ls[9])
    for IR in Piren_IR:
        print(IR)

    return Piren_IR, Piren_IR_ls
Example #4
0
def readingVIS_norm(ls_path_tif, filetif):
    #print("ls_path_tif :" , ls_path_tif)
    Piren_VIS_ls = []
    Piren_VIS_name = []
    mapping_columns = {}
    for path_tif in ls_path_tif:
        VIS_src = rio.open(os.path.join(path_tif))
        #print("VIS_src :",VIS_src)
        Piren_VIS_array = VIS_src.read()
        Piren_Limits = plotting_extent(VIS_src)  # Limites
        Piren_res = VIS_src.res  # resolution
        Piren_transform = VIS_src.transform
        Piren_VIS_ls.append(
            [Piren_VIS_array, Piren_Limits, VIS_src, Piren_transform])
        Piren_VIS_name.append(filetif)
    Piren_VIS = pd.DataFrame(
        np.array([
            Piren_VIS_ls[0][0], Piren_VIS_ls[0][1], Piren_VIS_ls[0][2],
            Piren_VIS_ls[0][3]
        ],
                 dtype=object).T,
        index=["VIS_array", "Limits", "VIS_src", "VIS_transform"],
        columns=['Phase_1'])

    #print("Piren_VIS.loc['VIS_src'][0]:",Piren_VIS.loc["VIS_src"][0])
    return Piren_VIS, Piren_VIS_ls
Example #5
0
def crop_resize(input_file, target_size_imgpath, output_file, geojson_file, crs, ch=0, normalization=False, rgb_nir=False, output_type=gdal.GDT_Byte):    
    
    # create extention
    with open(geojson_file, 'r+', encoding="utf-8") as f:
        gj = geojson.load(f)
    #pol = geometry.Polygon(gj['geometry']['coordinates'][0]) #['features'][-1]
    pol = geometry.Polygon(gj['features'][-1]['geometry']['coordinates'][0])
    
    # crop tif image
    with rasterio.open(target_size_imgpath) as f: #output_file 
        chm_crop, chm_crop_affine = mask(f,[pol],crop=True)
    
    if normalization:
        if rgb_nir:
            chm_crop = from_16_to_8(chm_crop[:-1], width=3)
        else:
            chm_crop = from_16_to_8(chm_crop, width=3)
    
    chm_extent = plotting_extent(chm_crop[0], chm_crop_affine)
    geotransform = (chm_crop_affine[2], chm_crop_affine[0], 0, chm_crop_affine[5], 0,chm_crop_affine[4])
    
    new_img = band_resize(input_file, target_size_imgpath)[0]
    
    print(new_img.shape, chm_crop[0].shape[1], chm_crop[0].shape[0])
    # save new cropped image chm_crop[0]
    dst_ds = gdal.GetDriverByName('GTiff').Create(output_file,  new_img.shape[1], new_img.shape[0], 1, output_type) 
    dst_ds.SetGeoTransform(geotransform)    # specify coords
    srs = osr.SpatialReference()            # establish encoding
    srs.ImportFromEPSG(crs) #32638  4326          
    dst_ds.SetProjection(srs.ExportToWkt()) # export coords to file
    dst_ds.GetRasterBand(1).WriteArray(new_img)   # write r-band to the raster
    dst_ds.FlushCache()                     # write to disk
    dst_ds = None
Example #6
0
def crop_aoi(input_file, output_file, geojson_file, output_type=gdal.GDT_Byte, crs=3857, value=1):    
    
    # export from jp2 to tif
    in_image = gdal.Open(input_file)
    driver = gdal.GetDriverByName("GTiff")
    #out_image = driver.CreateCopy(output_file, in_image, 0)
    in_image = None
    #out_image = None
    
    # create extention
    with open(geojson_file, 'r+', encoding="utf-8") as f:
        gj = geojson.load(f)
    pol = geometry.Polygon(gj['features'][-1]['geometry']['coordinates'][0])
    
    # crop tif image
    with rasterio.open(input_file, 'r+') as f: #output_file
        chm_crop, chm_crop_affine = mask(f,[pol],crop=True)
    
    chm_extent = plotting_extent(chm_crop[0], chm_crop_affine)
    geotransform = (chm_crop_affine[2], chm_crop_affine[0], 0, chm_crop_affine[5], 0,chm_crop_affine[4])
    
    #print(chm_crop.shape)
    # save new cropped image
    dst_ds = gdal.GetDriverByName('GTiff').Create(output_file,  chm_crop[0].shape[1], chm_crop[0].shape[0], 1, output_type) # gdal.GDT_UInt16)
    dst_ds.SetGeoTransform(geotransform)    # specify coords
    srs = osr.SpatialReference()            # establish encoding
    srs.ImportFromEPSG(crs)            
    dst_ds.SetProjection(srs.ExportToWkt()) # export coords to file
    dst_ds.GetRasterBand(1).WriteArray(chm_crop[0]*value)   # write r-band to the raster
    dst_ds.FlushCache()                     # write to disk
    dst_ds = None
Example #7
0
def cut_tiff(
    path_file,
    mapped_shapefile,
):
    with rio.open(path_file) as src:
        crop, crop_affine = mask(src, [mapped_shapefile],
                                 crop=True,
                                 nodata=NODATA)

    crop_extent = plotting_extent(crop[0], crop_affine)

    return crop, crop_extent
Example #8
0
def plot_select_class_prediction(class_prediction, color_map, classes,
                                 figsize=(10,10), fontsize=8, r_obj=None,
                                 save=False, path=None):

    # find the highest pixel value in the prediction image
    n = int(np.max(class_prediction[:,:,0]))


    # create a default white color map using colors as float 0-1
    index_colors = [(1.0, 1.0, 1.0) for key in range(0, n )]

    # Replace index_color with the one you want to visualize
    for cl in classes:
        idx = list(color_map[cl].keys())[0]
        vals = list(color_map[cl].values())[0]
        # Transform 0 - 255 color values from colors as float 0 - 1
        _v = [_v / 255.0 for _v in vals]
        index_colors[idx] = tuple(_v)

    cmap = plt.matplotlib.colors.ListedColormap(index_colors, 'Classification', n)


    from matplotlib.patches import Patch
    # Create a list of labels sorted by the int of color_map
    class_labels = [el[0] for el in sorted(color_map.items(), key=lambda label: label[1].keys())]
    # A path is an object drawn by matplotlib. In this case a patch is a box draw on your legend
    # Below you create a unique path or box with a unique color - one for each of the labels above
    legend_patches = [Patch(color=icolor, label=label)
                      for icolor, label in zip(index_colors, class_labels)]

    # Plot Classification
    fig, axs = plt.subplots(1,1,figsize=figsize)
    axs.imshow(class_prediction[:,:,0], cmap=cmap, interpolation='none')
    if r_obj:
        from rasterio.plot import plotting_extent
        axs.imshow(class_prediction[:,:,0], extent=plotting_extent(r_obj), cmap=cmap, interpolation='none')

    axs.legend(handles=legend_patches,
              facecolor="white",
              edgecolor="white",
              bbox_to_anchor=(1.20, 1),
              fontsize=fontsize)  # Place legend to the RIGHT of the map
    axs.set_axis_off()
    plt.show()
    if save and path:
        fig.savefig(path, bbox_inches='tight')

    def show_hist(path_to_raster):
        """
        (to be modified)
        """
        with rasterio.open(path_to_raster) as dataset:
            rasterio.plot.show_hist(dataset.read([1,2,3,4]), bins=50, histtype='stepfilled', lw=0.0, stacked=False, alpha=0.3)
Example #9
0
def points_on_layer_plot(src, arr, gdf, n, **kwargs):

    cmap, marker, markersize, color, label = kwargs.get('cmap',"pink"), \
                              kwargs.get('marker',"s"), \
                              kwargs.get('markersize',30), \
                              kwargs.get('color',"purple"), \
                              kwargs.get('label',"classname")
    # Plotting
    fig = plt.figure(n, figsize=(8, 8))
    ax1 = plt.subplot(2, 1, 1)
    gdf.plot(ax=ax1,
             marker=marker,
             markersize=markersize,
             color=color,
             label=label)

    ax1.imshow(
        arr,
        # Set the spatial extent or else the data will not line up with your geopandas layer
        extent=plotting_extent(src),
        cmap=cmap)
    ax2 = plt.subplot(2, 1, 2, sharex=ax1, sharey=ax1)
    ax2.imshow(arr, extent=plotting_extent(src), cmap=cmap)
Example #10
0
def plot_crop_overlayed_on_raster():
    fig, ax = plt.subplots(figsize=(10, 8))

    ep.plot_bands(raster.read(1),
                  cmap='terrain',
                  extent=plotting_extent(raster),
                  ax=ax,
                  title="Raster Layer with Shapefile Overlayed",
                  cbar=False)

    crop_extent.plot(ax=ax, alpha=.8)
    ax.set_axis_off()

    plt.show()
Example #11
0
def readingIR(ls_path_tif, filetif):
    Piren_IR_ls = []
    Piren_IR_name = []
    mapping_columns = {}
    for path_tif in ls_path_tif:
        IR_src = rio.open(os.path.join(path_tif))
        Piren_IR_array = IR_src.read(1)  # Lit la bande 1
        Piren_Limits = plotting_extent(IR_src)  # Limites
        Piren_res = IR_src.res  # resolution
        Piren_IR_ls.append([Piren_IR_array, Piren_Limits, IR_src])
    Piren_IR_name.append(filetif)
    Piren_IR = pd.DataFrame(np.array(
        [Piren_IR_ls[0][0], Piren_IR_ls[0][1], Piren_IR_ls[0][2]],
        dtype=object).T,
                            index=["IR_array", "Limits", "IR_src"],
                            columns=['IR_' + filetif[0]])

    return Piren_IR, Piren_IR_ls
Example #12
0
def alternative_readingIR_all(ls_path_tif, filetif):
    Piren_IR_ls = []
    Piren_IR_name = []
    mapping_columns = {}
    dict_IR = {}
    for k, path_tif in enumerate(ls_path_tif):
        with rio.open(os.path.join(path_tif)) as IR_src:
            Piren_IR_array = IR_src.read(1)  # Lit la bande 1
            Piren_Limits = plotting_extent(IR_src)  # Limites
            Piren_res = IR_src.res  # resolution
            dict_IR["IR_" + filetif[k]] = {
                "Piren_IR_array": Piren_IR_array,
                "Piren_Limits": Piren_Limits,
                "Piren_res": Piren_res,
                "IR_src": IR_src
            }

        print("completed :", "IR_" + filetif[k])

    return dict_IR
Example #13
0
def normalization(input_file, geojson_file, normalization=False, rgb_nir=False, output_type=gdal.GDT_Byte):    
    bands_10m = ['B02','B03','B04', 'B08'] 
    bands_20m = ['B05','B06','B07','B8A','B11', 'B12'] 
    
    ## change crs
    #input_raster = gdal.Open(input_file)#output_file)
    #output_raster = output_file 
    #gdal.Warp(output_raster,input_raster,dstSRS='EPSG:4326')
    
    # create extention
    with open(geojson_file, 'r+', encoding="utf-8") as f:
        gj = geojson.load(f)
    pol = geometry.Polygon(gj['geometry']['coordinates'][0]) #['features'][-1]
    
    with rasterio.open(input_file) as src:
        size_x = src.width
        size_y = src.height
        
    chm_crop = np.zeros((len(bands_10m + bands_20m), size_y, size_x))
    # crop tif image
    for ind, band_name in enumerate(bands_10m + bands_20m):
        with rasterio.open(input_file[:-11]+band_name+'_10m.tif') as f: #output_file
            chm_crop[ind], chm_crop_affine = mask(f,[pol],crop=True)
    
    if normalization:
        chm_crop = from_16_to_8(chm_crop, width=3)

    chm_extent = plotting_extent(chm_crop[0], chm_crop_affine)
    geotransform = (chm_crop_affine[2], chm_crop_affine[0], 0, chm_crop_affine[5], 0,chm_crop_affine[4])
    
    for ind, band_name in enumerate(bands_10m + bands_20m):
        # save new cropped image
        output_file = input_file[:-11]+band_name+'_10m_norm.tif'
        dst_ds = gdal.GetDriverByName('GTiff').Create(output_file,  chm_crop[0].shape[1], chm_crop[0].shape[0], 1, output_type) 
        dst_ds.SetGeoTransform(geotransform)    # specify coords
        srs = osr.SpatialReference()            # establish encoding
        srs.ImportFromEPSG(32638) #  4326          
        dst_ds.SetProjection(srs.ExportToWkt()) # export coords to file
        dst_ds.GetRasterBand(1).WriteArray(chm_crop[ind])   # write r-band to the raster
        dst_ds.FlushCache()                     # write to disk
        dst_ds = None
    def crop(self, src_dir, dest_dir, vmin=0, vmax=1000, plot=False):
        status = True

        file_name = f'{self.clim_type}_{self.month:02d}'

        temp_file = os.path.join(dest_dir, f'{file_name}_temp.{self.ext}')
        cropped_file = os.path.join(dest_dir, f'{file_name}.{self.ext}')
        # file_out = os.path.join(dest_dir, f'{file_name}_r.{ext}')

        try:
            # Scans dir and find file_name as substring from dir tree
            src_file = util.get_file_in_dir(file_name, src_dir)

            clim_data, clim_metadata = self._pre_crop(src_file, SHAPE_FILE)
            clim_data_affine = clim_metadata['transform']

            # Create spatial plotting extent for the cropped layer
            clim_data_extent = plotting_extent(clim_data[0], clim_data_affine)

            if plot:
                cmap = self._set_negative_color(color='w')
                title = '{} {}'.format(self.clim_types[clim_type], self.month)

                self._plot(clim_data[0], clim_data_extent, cmap,
                    title=title, vmin=vmin, vmax=vmax)

            self._crop_extent(temp_file, clim_data, clim_metadata, clim_data_affine)
            self._warp(temp_file, cropped_file, SHAPE_FILE)

            os.remove(temp_file)
        
        except Exception as err:
            print(err)
            status = False
        
        return status
Example #15
0
def rgb_image():
    """Fixture holding an RGB image for plotting"""
    with rio.open(path_to_example("rmnp-rgb.tif")) as src:
        rgb = src.read()
        ext = plotting_extent(src)
    return rgb, ext
Example #16
0
def plot_objects(obj=None,
                 img=None,
                 column=None,
                 bounds_only=True,
                 obj_extent=True,
                 obj_cmap=None,
                 linewidth=0.5,
                 alpha=1,
                 edgecolor='white',
                 rgb=[4, 2, 1],
                 band=None,
                 plot_window=None,
                 ax=None,
                 obj_kwargs={},
                 img_kwargs={}):
    """Plot vector objects on an image
    Parameters:
        """
    # Create a figure and ax is not provided
    if not ax:
        fig, ax = plt.subplots(1, 1, figsize=(15, 15))
    # Plot the img if provided
    if img is not None:
        logger.debug('Plotting imagery...')
        # If path to image provided, open it, otherwise assumed open rasterio DatasetReader
        if isinstance(img, str):
            img = rio.open(img)
        img_arr = img.read(masked=True)

        if obj is not None and obj_extent:
            logger.debug('Using objects extent for plotting.')
            minx, miny, maxx, maxy = obj.total_bounds
            minrow, mincol = geo2pixel(y=maxy, x=minx, img=img)
            maxrow, maxcol = geo2pixel(y=miny, x=maxx, img=img)
            img_arr = img_arr[:, mincol:maxcol, minrow:maxrow]
            logger.debug("Object ext: {} {} {} {}".format(
                minx, miny, maxx, maxy))
            img_ext = (minx, miny, maxx, maxy)
        else:
            logger.debug('Using images full extent for plotting.')
            # minx, maxx, miny, maxy = plotting_extent(img)
            # img_ext = (minx, miny, maxx, maxy)
            img_ext = plotting_extent(img)

        if not band and img_arr.shape[0] == 1:
            band = 1
        if band is not None:
            ep.plot_bands(img_arr[band - 1],
                          extent=img_ext,
                          ax=ax,
                          **img_kwargs)
        else:
            ep.plot_rgb(img_arr, rgb=rgb, ax=ax, extent=img_ext, **img_kwargs)

    # Plot the objects if provided
    if obj is not None:
        logger.debug('Plotting objects...')
        if img is not None:
            obj = obj.to_crs(img.crs)
        # If a column is not provided, plot all as the same color
        if column is None:
            # Create temporary column, ensuring it doesn't exist
            logger.debug('Creating a temporary column for plotting')
            column = np.random.randint(10000)
            while column in list(obj):
                column = 'temp_{}'.format(np.random.randint(10000))

            obj[column] = 1
        if bounds_only:
            logger.debug('Plotting objects...')
            obj.set_geometry(obj.geometry.boundary).plot(ax=ax,
                                                         column=column,
                                                         cmap=obj_cmap,
                                                         alpha=alpha,
                                                         linewidth=linewidth,
                                                         **obj_kwargs)
        else:
            obj.plot(ax=ax,
                     column=column,
                     cmap=obj_cmap,
                     alpha=alpha,
                     linewidth=linewidth,
                     edgecolor=edgecolor,
                     **obj_kwargs)
    if plot_window:
        logger.debug('Updating to use passed window as extent.')
        ax.set_xlim([plot_window[0], plot_window[2]])
        ax.set_ylim([plot_window[1], plot_window[3]])

    fig.show()

    return fig, ax
Example #17
0
        dir_crop = dir_iii + '\\crop'

        list_iii = glob.glob('*.tif')

        # iii = list_iii[1]

        for iii in list_iii:

            with rio.open(iii) as iii_tif:
                iii_tif_crop, iii_tif_crop_meta = es.crop_image(
                    iii_tif, crop_extent)

            iii_tif_crop_affine = iii_tif_crop_meta['transform']

            # Create spatial plotting extent for the cropped layer
            iii_tif_extent = plotting_extent(iii_tif_crop[0],
                                             iii_tif_crop_affine)

            # Plot your data
            '''
            ep.plot_bands(iii_tif_crop[0],
                          extent = iii_tif_extent,
                          cmap = 'Greys',
                          title = "Cropped Raster Dataset",
                          scale = False)
            plt.show()
            '''

            # Update with the new cropped affine info and the new width and height
            iii_tif_crop_meta.update({
                'transform': iii_tif_crop_affine,
                'height': iii_tif_crop.shape[1],
# Stack Landsat bands

os.chdir(os.path.join(et.io.HOME, "earth-analytics"))
array, raster_prof = es.stack(stack_band_paths, out_path=raster_out_path)

####################################################################################
# Create Extent Object
# --------------------------------
# To get the raster extent, use the ``plotting_extent`` function on the
# array from ``es.stack()`` and the Rasterio profile or metadata object. The function
# needs a single
# layer of a numpy array, which is why we use ``arr[0]``. The function also
# needs the spatial transformation for the Rasterio object, which can be acquired by accessing
# the ``"transform"`` key within the Rasterio Profile.

extent = plotting_extent(array[0], raster_prof["transform"])

################################################################################
# Plot Un-cropped Data
# ------------------------------
# You can see the boundary and the raster before the crop using ``ep.plot_rgb()``
# Notice that the data appear washed out.

fig, ax = plt.subplots(figsize=(12, 12))
ep.plot_rgb(
    array,
    ax=ax,
    stretch=True,
    extent=extent,
    str_clip=0.5,
    title="RGB Image of Un-cropped Raster",
    "data", "cold-springs-fire", "landsat_collect",
    "LC080340322016070701T1-SC20180214145604", "crop", "*band*.tif")

landsat_paths_pre = glob(landsat_paths_pre_path)
landsat_paths_pre.sort()

# Stack the Landsat pre fire data
landsat_pre_st_path = os.path.join("data", "cold-springs-fire", "outputs",
                                   "landsat_pre_st.tif")

es.stack(landsat_paths_pre, landsat_pre_st_path)

# Read landsat pre fire data
with rio.open(landsat_pre_st_path) as landsat_pre_src:
    landsat_pre = landsat_pre_src.read(masked=True)
    landsat_extent = plotting_extent(landsat_pre_src)

ep.plot_rgb(
    landsat_pre,
    rgb=[3, 2, 1],
    extent=landsat_extent,
    title=
    "Landsat True Color Composite Image | 30 meters \n Post Cold Springs Fire \n July 8, 2016"
)

plt.show()
# -

# Notice in the data above there is a large cloud in your scene. This cloud will impact any quantitative analysis that you perform on the data. You can remove cloudy pixels using a mask. Masking "bad" pixels:
#
# 1. Allows you to remove them from any quantitative analysis that you may perform such as calculating NDVI.
Example #20
0
def plot_select_class_prediction(class_prediction,
                                 mapping,
                                 color_map,
                                 classes,
                                 figsize=(10, 10),
                                 fontsize=8,
                                 src=None,
                                 save=False,
                                 path=None):

    # find the highest pixel value in the prediction image
    #n = int(np.max(class_prediction[0,:,:]))
    n = len(color_map)

    # create a default white color map using colors as float 0-1
    index_colors = [(1.0, 1.0, 1.0) for key in range(0, n)]

    for cl, val in color_map.items():
        # convert the class_prediction values to match the plotting values
        class_prediction = np.where(class_prediction == int(mapping[cl]),
                                    [*val][0], class_prediction)

    # Replace index_color with the one you want to visualize
    for cl in classes:
        idx = list(color_map[cl].keys())[0]
        vals = list(color_map[cl].values())[0]
        # Transform 0 - 255 color values from colors as float 0 - 1
        _v = [_v / 255.0 for _v in vals]
        index_colors[idx] = tuple(_v)

    #pdb.set_trace()

    cmap = plt.matplotlib.colors.ListedColormap(index_colors)

    from matplotlib.patches import Patch
    # Create a list of labels sorted by the int of color_map
    class_labels = [
        el[0]
        for el in sorted(color_map.items(), key=lambda label: label[1].keys())
    ]
    # A path is an object drawn by matplotlib. In this case a patch is a box draw on your legend
    # Below you create a unique path or box with a unique color - one for each of the labels above
    legend_patches = [
        Patch(color=icolor, label=label)
        for icolor, label in zip(index_colors, class_labels)
    ]

    # Plot Classification
    fig, axs = plt.subplots(1, 1, figsize=figsize)
    axs.imshow(class_prediction, cmap=cmap, interpolation='none')
    if src:
        from rasterio.plot import plotting_extent
        axs.imshow(class_prediction,
                   extent=plotting_extent(src),
                   cmap=cmap,
                   interpolation='none')

    axs.legend(handles=legend_patches,
               facecolor="white",
               edgecolor="white",
               bbox_to_anchor=(1.20, 1),
               fontsize=fontsize)  # Place legend to the RIGHT of the map
    axs.set_axis_off()
    plt.show()
    if save and path:
        fig.savefig(path, bbox_inches='tight')
Example #21
0
def main(fname, band, title, save, vmax, vmin, colorbar):
    if title is None:
        title = fname
    palette = copy(plt.cm.viridis)
    palette.set_over('r', 1.0)
    palette.set_under('k', 1.0)
    #palette.set_bad('#0e0e2c', 1.0)
    palette.set_bad('w', 1.0)

    src = rasterio.open(fname)
    data = read_array(src, band)
    if too_big(src):
        rmin = data.min()
        rmax = data.max()
    else:
        rmin, rmax = get_min_max(fname)

    if vmax is None:
        vmax = rmax
    if vmin is None:
        vmin = rmin

    dpi = 100.0
    size = [data.shape[2] / dpi, data.shape[1] / dpi]
    if colorbar:
        size[1] += 70 / dpi
        pass

    if save:
        fig = plt.figure(figsize=size, dpi=dpi)
        ax = plt.gca()
        show(data,
             ax=ax,
             cmap=palette,
             title=title,
             vmin=vmin,
             vmax=vmax,
             extent=plotting_extent(src))
        fig.tight_layout()
        #ax.axis('off')
        if colorbar:
            divider = make_axes_locatable(ax)
            cax = divider.append_axes("bottom", size="5%", pad=0.25)
            plt.colorbar(ax.images[0], cax=cax, orientation='horizontal')
        fig.savefig(save, transparent=False)
        plt.show()
    else:
        fig = plt.figure(figsize=size, dpi=dpi)
        ax = plt.gca()
        show(data,
             ax=ax,
             cmap=palette,
             title=title,
             vmin=vmin,
             vmax=vmax,
             extent=plotting_extent(src))
        if colorbar:
            divider = make_axes_locatable(ax)
            cax = divider.append_axes("bottom", size="5%", pad=0.25)
            plt.colorbar(ax.images[0], cax=cax, orientation='horizontal')
        plt.show()
Example #22
0
with rio.open(stack_band_paths[0]) as raster_crs:
    raster_profile = raster_crs.profile
    bound_utm13N = bound.to_crs(raster_profile["crs"])

################################################################################
# Create a Plot With the Boundary overlayed on the RGB Image
# ----------------------------------------------------------
# You can plot a polygon boundary over an image by creating a raster extent
# for the plot using the ``plotting_extent`` function from ``rasterio.plot``.
# The function needs the Rasterio profile of the image and a single layer of a
# numpy array, which can be specified with ``arr_str[0]``. The function also
# needs the spatial transformation for the Rasterio object, which can be acquired
# by accessing the ``"transform"`` key within the Rasterio profile.

# Create raster extent for the plot
extent = plotting_extent(arr_st[0], raster_profile["transform"])

# Create figure with one plot
fig, ax = plt.subplots(figsize=(12, 12))

# Plot boundary with high zorder for contrast
bound_utm13N.boundary.plot(ax=ax, color="black", zorder=10)

# Plot CIR image using the raster extent
ep.plot_rgb(
    arr_st,
    rgb=(4, 3, 2),
    ax=ax,
    stretch=True,
    extent=extent,
    str_clip=0.5,
# Stack Landsat bands

os.chdir(os.path.join(et.io.HOME, "earth-analytics"))
array, raster_prof = es.stack(stack_band_paths, out_path=raster_out_path)

####################################################################################
# Create Extent Object
# --------------------------------
# To get the raster extent, use the ``plotting_extent`` function on the
# array from ``es.stack()`` and the Rasterio profile or metadata object. The function
# needs a single
# layer of a numpy array, which is why we use ``arr[0]``. The function also
# needs the spatial transformation for the Rasterio object, which can be acquired by accessing
# the ``"transform"`` key within the Rasterio Profile.

extent = plotting_extent(array[0], raster_prof["transform"])

################################################################################
# Plot Un-cropped Data
# ------------------------------
# You can see the boundary and the raster before the crop using ``ep.plot_rgb()``
# Notice that the data appear washed out.

fig, ax = plt.subplots(figsize=(12, 12))
ep.plot_rgb(
    array,
    ax=ax,
    stretch=True,
    extent=extent,
    str_clip=0.5,
    title="RGB Image of Un-cropped Raster",
Example #24
0
fig, ax = plt.subplots(figsize=(10, 10))
ax.imshow(map_im, cmap='terrain', extent=extent)
cerrado_sh.plot(ax=ax, alpha=.6, color='g')

# +

extent_geojson = mapping(cerrado_sh.geometry[0])
extent_geojson

# +
with rio.open(path_file) as src:
    cerrado_crop, cerrado_crop_affine = mask(src, [extent_geojson],
                                             crop=True,
                                             nodata=NODATA)

cerrado_extent = plotting_extent(cerrado_crop[0], cerrado_crop_affine)
# -

cerrado_crop

# Tranformo o array acima em um masked array, para conseguir printar sem os NODATAS

cerrado_masked = np.ma.masked_where(cerrado_crop[0] == NODATA, cerrado_crop[0])

cerrado_masked

# +
plt.figure(figsize=(10, 10))
plt.imshow(cerrado_masked, cmap="terrain", extent=cerrado_extent)

plt.colorbar()
Example #25
0
    vector = gp.read_file(vfp)
    print(vector)
    print(vector.crs)
    print()

    print()
    vector = vector.to_crs(raster.crs)

    # our crop_extent is the vector
    crop_extent = vector

    raster_crop, raster_crop_meta = es.crop_image(raster, crop_extent)
    raster_crop_affine = raster_crop_meta["transform"]

    # Create spatial plotting extent for the cropped layer
    raster_extent = plotting_extent(raster_crop[0], raster_crop_affine)

    print(crop_extent)

    plot_crop_extent()

    plot_crop_overlayed_on_raster()

    plot_cropped_raster()

    raster_meta = raster.profile
    raster_meta.update({
        'transform': raster_crop_affine,
        'height': raster_crop.shape[1],
        'width': raster_crop.shape[2],
        'nodata': 0.0,
Example #26
0
all_landsat_bands.sort()
"""setting our output file path"""
landsat_post_fire_path = "data/cold-springs-fire/outputs/landsat_post_fire.tif"
"""es.stack will stack all bands on top of one another.
making raster values more easily comparable."""
es.stack_raster_tifs(all_landsat_bands, landsat_post_fire_path)

# we can clip the files but in this case we use .read()
"""the next 5 lines will open the file, set up profile, set up bounding box,
our plotting extent, and validates that our data has values assigned to array"""

with rio.open(landsat_post_fire_path) as src:
    landsat_post_fire = src.read(masked=True)
    landsat_post_meta = src.profile
    landsat_post_bounds = src.bounds
    landsat_extent = plotting_extent(src)

# Open fire boundary layer and reproject it to match the Landsat data
fire_boundary_path = "data/cold-springs-fire/vector_layers/fire-boundary-geomac/co_cold_springs_20160711_2200_dd83.shp"
fire_boundary = gpd.read_file(fire_boundary_path)

# If the CRS' are not the same be sure to reproject
"""this reprojects the coordinate reference system for the fire boundary"""
fire_bound_utmz13 = fire_boundary.to_crs(landsat_post_meta['crs'])

#calculating NBR postfire and plotting results
"""this calculates postfire NBR"""
landsat_postfire_nbr = (landsat_post_fire[4] - landsat_post_fire[6]) / (
    landsat_post_fire[4] + landsat_post_fire[6])
"""sets plot parameters"""
fig, ax = plt.subplots(figsize=(12, 6))
Example #27
0
def main(metric, scenario, start, limit, out, dst_crs):
    palette = copy(plt.cm.viridis_r)
    palette.set_under('y', 1.0)
    palette.set_over('r', 1.0)
    palette.set_bad('w', 1.0)

    fname = '/out/luh2/%s-%s-%d.tif' % (scenario, metric, 2100)
    with rasterio.open(fname) as src:
        meta = src.meta
        end = src.read(1, masked=True)
        stack = read_historical(start, 2015, src.bounds, metric)
    inc = ma.where(stack < end, 1, 0)
    years = inc.sum(axis=0)
    years2 = ma.where(end > stack[-1],
                      ma.where(end > stack[0], start - 1, 2015 - years), 2016)
    mask = ma.where((end > limit) & (stack[-1] > limit), True, False)
    years2.mask = np.logical_or(years2.mask, mask)
    years2.fill_value = src.nodata

    if out:
        meta_out = meta.copy()
        meta_out['dtype'] = 'int32'
        with rasterio.open(out.name, 'w', **meta_out) as dst:
            dst.write(years2.filled(meta_out['nodata']).astype(np.int32),
                      indexes=1)
    title = 'Year to which BII recovers by 2100'
    vmin = start - 2
    vmax = 2015
    dpi = 100.0
    size = [years2.shape[1] / dpi, years2.shape[0] / dpi]
    size[1] += 70 / dpi
    fig = plt.figure(figsize=size, dpi=dpi)
    if dst_crs:
        with rasterio.open(out.name) as src:
            data = src.read(
                1,
                masked=True,
                window=src.window(  #*src.bounds))
                    *(-180, -90, 180, 90)))
            #crs = ccrs.Robinson()
            crs = ccrs.Mollweide()
            dst_crs = crs.proj4_params
            (dst_transform, dst_width, dst_height, dst_data) = project(
                dst_crs,
                src,
                data,  #src.bounds)
                (-180, -90, 180, 90))
        xmin, ymax = dst_transform * (0, 0)
        xmax, ymin = dst_transform * (dst_width, dst_height)
        #taff = Affine.from_gdal(-18040068.169145808, 25055.6578813187,
        #                        0.0, 9020047.848073646, 0.0, -25055.6578813187)
        #xmin, ymax = taff * (0, 0)
        #xmax, ymin = taff * (1436, 728)
        ax = plt.axes(projection=crs)
        ax.imshow(dst_data,
                  origin='upper',
                  extent=[xmin, xmax, ymin, ymax],
                  cmap=palette,
                  vmin=vmin,
                  vmax=vmax)
        ax.coastlines()
        #ax.set_title(title, fontweight='bold')
        sm = matplotlib.cm.ScalarMappable(cmap=palette,
                                          norm=plt.Normalize(1900, 2015))
        sm._A = []
        cb = plt.colorbar(sm, orientation='vertical')
        cb.set_label(title)
    else:
        ax = plt.gca()
        show(years2,
             ax=ax,
             cmap=palette,
             title=title,
             vmin=vmin,
             vmax=vmax,
             extent=plotting_extent(src))
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("bottom", size="5%", pad=0.25)
        plt.colorbar(ax.images[0], cax=cax, orientation='horizontal')
    fig.tight_layout()
    #ax.axis('off')
    if out:
        fig.savefig(out.name.replace('.tif', '.png'), transparent=False)
    plt.show()

    #show(years2, cmap=palette, vmin=start, vmax=2100)
    #pdb.set_trace()
    pass
Example #28
0
print(("\nNow doing some data science (running PCA, "
       "then finding your city's nearest neighbors)...\n"))
pca = PCA(n_components=19)
pcs = pca.fit_transform(bioclim_data)

# find nearest neighbor of last row (i.e. target city)
kdt = KDTree(pcs[:-1, ], leaf_size=30, metric='euclidean')
analog_idxs = kdt.query(pcs[-1].reshape((1, pcs.shape[1])), k=50)[1].ravel()
analogs = cities.iloc[analog_idxs][['CITY_NAME', 'CNTRY_NAME']]
print("Here are your top 50 climate sister cities:\n")
print(analogs)

# plot
fig, ax = plt.subplots(figsize=(10, 10))
ep.plot_bands(clim[0, :, :],
              extent=plotting_extent(clim_src),
              cmap='Greys',
              title='%s and its climate sister cities' % target,
              scale=False,
              ax=ax)
cities.iloc[analog_idxs, :].plot(ax=ax,
                                 marker='o',
                                 markersize=100,
                                 cmap='YlGn_r')
cities[cities.CITY_NAME == target].plot(ax=ax,
                                        marker='*',
                                        markersize=100,
                                        color='purple')
ax.set_axis_off()
plt.show()
    ax.set_xlim(p_bbox[0], p_bbox[1])
    ax.set_ylim(p_bbox[2], p_bbox[3])
    ax.add_artist(ScaleBar(dx=1, box_alpha=0.1, location='lower left'))
    print(family)
    print(species)
    #ax.set_title(family+ " - "+ species)
    plt.savefig(output_map + family + "_" + species + ".png", dpi=300)
    plt.close('all')


# main
transformer = Transformer.from_crs("epsg:4326", "epsg:3857", always_xy=True)
bbox_all = [28.9, 31, -4.7, -2.2]
raster_data = rxr.open_rasterio(fp, masked=True).rio.reproject("epsg:3857")

raster_data_extent = plotting_extent(raster_data[0],
                                     raster_data.rio.transform())

bbox_1 = transformer.transform(bbox_all[0], bbox_all[2])
bbox_2 = transformer.transform(bbox_all[0], bbox_all[3])
bbox_3 = transformer.transform(bbox_all[1], bbox_all[3])
bbox_4 = transformer.transform(bbox_all[1], bbox_all[2])

bbox_conv = [bbox_1[0], bbox_4[0], bbox_1[1], bbox_3[1]]

xticks = []
jticks = []
xlabels = []
jlabels = []
i = bbox_all[0]
while i <= bbox_all[1]:
    #print(i)