Exemplo n.º 1
0
def test_show_raster_mult_bands():
    """Test multiple bands plotting."""
    matplotlib = pytest.importorskip('matplotlib')
    with rasterio.open('tests/data/RGB.byte.tif') as src:
        show((src, (1, 2, 3)))
        fig = plt.gcf()
        plt.close(fig)
Exemplo n.º 2
0
def test_show_raster_band():
    """Test plotting a single raster band."""
    matplotlib = pytest.importorskip('matplotlib')
    with rasterio.open('tests/data/RGB.byte.tif') as src:
        show((src, 1))
        fig = plt.gcf()
        plt.close(fig)
Exemplo n.º 3
0
def test_show_raster_float():
    """Test plotting a raster object with float data."""
    matplotlib = pytest.importorskip('matplotlib')
    with rasterio.open('tests/data/float.tif') as src:
        show(src)
        fig = plt.gcf()
        plt.close(fig)
Exemplo n.º 4
0
        def view_mosaic():
            assert self.ensure_variables(
                (self.out_path,
                 True)), "Please run steps before (mosaic sections)!"

            with rasterio.open(self.out_path) as src:
                _, ax = plt.subplots(nrows=1, ncols=1, figsize=(12, 12))

                show(src, ax=ax)
                plt.show()
Exemplo n.º 5
0
def inundation_map(inun_map,lu_raster=False,lu_vector=False,save=False,**kwargs):
    """
    Arguments:
        *inun_map* : GeoTiff with inundation depth per grid cell.

    Optional Arguments:
        *lu_raster* : Set to **True** if you would like to use the landuse raster 
        as background.
            
        *lu_vector* : Set to **True** if you would like to use the landuse raster 
        as background.
        
        *save* : Set to **True** if you would like to save the output. Requires 
        several **kwargs**
        
    kwargs:
        *landuse_map* : Path to land-use map.
        
        *output_path* : Specify where files should be saved.
        
        *scenario_name*: Give a unique name for the files that are going to be saved.
        
    """    
    if (lu_raster == False) & (lu_vector == False):
        fig, ax = plt.subplots(1, 1,figsize=(12,10))

        ax.set_xticks([])
        ax.set_yticks([])
        ax.set_axis_off()
        
    elif (lu_raster == False) & (lu_vector == True):
        landuse = kwargs['landuse_map']
        ax = landuse_vector(landuse)

    elif (lu_raster == True) & (lu_vector == False):
        landuse = kwargs['landuse_map']
        ax = landuse_raster(landuse)
        
    with rasterio.open(inun_map) as src:
        inundation = numpy.array(src.read()[0,:,:],dtype=float)
        inundation[inundation == 0] = numpy.nan

        max_value = 6
        show(inundation,ax=ax,cmap='Blues',transform=src.transform,zorder=2,vmax=max_value)

    if save:
        if 'output_path' in kwargs:
            output_path = kwargs['output_path']
            if not os.path.exists(output_path):
                os.mkdir(output_path)
        if 'scenario_name' in kwargs:
            scenario_name = kwargs['scenario_name']

        fig.tight_layout()
        fig.savefig(os.path.join(output_path,'inundation_{}.png'.format(scenario_name)),dpi=350, bbox_inches='tight')
def mosaic_creator(base_path=None, show_flag=False, requested_indices=None, test=False):

    print("================")
    print("Creating Mosaics")
    indice_list = ["ndmi", "ndvi", "savi", "msavi", "ndwi"]
    choice = []
    for idx, boolean in enumerate(requested_indices):
        if boolean == True:
            choice.append(idx)
    indices = [indice_list[i] for i in requested_indices]
    date_list = ["Start_date", "End_date"]

    for date in date_list:
        paths = glob.glob(os.path.join(base_path, "**/{}".format(date)), recursive=True)
        path = paths[0]
        print(path)
        # index_dict = {index: [] for index in indices}
        for index in indices:
            print("Creating index {} for {}".format(index, " ".join(date.split('_'))))
            index_image = glob.glob("{}/**/*clipped_{}*".format(path, index), recursive=True)
            # print(index_image)

            src_files_to_mosaic = []
            for file in index_image:
                src = rasterio.open(file)
                src_files_to_mosaic.append(src)
            # print(src_files_to_mosaic)

            mosaic, out_trans = merge(src_files_to_mosaic)
            if show_flag:
                show(mosaic, cmap="terrain")
                plt.waitforbuttonpress()

            out_meta = src_files_to_mosaic[0].meta.copy()
            out_meta.update({"driver": "GTiff",
                             "height": mosaic.shape[1],
                             "width": mosaic.shape[2],
                             "transform": out_trans
                             }
                            )
            try:
                try:
                    os.chdir(os.path.join(path, 'mosaics'))
                except FileNotFoundError:
                    os.mkdir(os.path.join(path, 'mosaics'))
                    os.chdir(os.path.join(path, 'mosaics'))

                with rasterio.open("{}_mosaic_{}.tiff".format(date, index), "w",
                                   **out_meta) as destination:
                    destination.write(mosaic)
                os.chdir(base_path)
            except IndexError:
                pass
    print("Mosaics created successfully!!!")
Exemplo n.º 7
0
def plot_s2_cloud_prob_image(file_path: str, **kwargs):

    # open image with rasterio
    with rasterio.open(file_path) as src:
        # assert the image has 15 channels
        assert src.meta["count"] == 15

        # plot image
        rasterioplt.show(src.read(15), transform=src.transform, **kwargs)

    return None
    def plot(self, ax=None, contour=False, **kwargs):
        """
        Method to plot raster layers or contours.

        Parameters
        ----------
        ax : matplotlib.pyplot.axes
            optional matplotlib axes for plotting
        contour : bool
            flag to indicate creation of contour plot

        **kwargs :
            matplotlib keyword arguments
            see matplotlib documentation for valid
            arguments for plot and contour.

        Returns
        -------
            ax : matplotlib.pyplot.axes

        """
        if rasterio is None:
            msg = 'Raster().plot(): error ' + \
                  'importing rasterio - try "pip install rasterio"'
            raise ImportError(msg)
        else:
            from rasterio.plot import show

        if self._dataset is not None:
            ax = show(self._dataset, ax=ax, contour=contour, **kwargs)

        else:
            d0 = len(self.__arr_dict)
            d1, d2 = None, None
            for _, arr in self.__arr_dict.items():
                d1, d2 = arr.shape

            if d1 is None:
                raise AssertionError("No plottable arrays found")

            data = np.zeros((d0, d1, d2), dtype=float)
            i = 0
            for _, arr in sorted(self.__arr_dict.items()):
                data[i, :, :] = arr
                i += 1

            data = np.ma.masked_where(data == self.nodatavals, data)
            ax = show(data,
                      ax=ax,
                      contour=contour,
                      transform=self._meta["transform"],
                      **kwargs)

        return ax
Exemplo n.º 9
0
def test_show_array3D():
    """
    This test only verifies that code up to the point of plotting with
    matplotlib works correctly.  Tests do not exercise matplotlib.
    """
    with rasterio.open('tests/data/RGB.byte.tif') as src:
        try:
            show(src.read((1, 2, 3)))
            fig = plt.gcf()
            plt.close(fig)
        except ImportError:
            pass
Exemplo n.º 10
0
def test_show_array3D():
    """
    This test only verifies that code up to the point of plotting with
    matplotlib works correctly.  Tests do not exercise matplotlib.
    """
    with rasterio.open('tests/data/RGB.byte.tif') as src:
        try:
            show(src.read((1, 2, 3)))
            fig = plt.gcf()
            plt.close(fig)
        except ImportError:
            pass
Exemplo n.º 11
0
def test_show_raster_title():
    """
    This test only verifies that code up to the point of plotting with
    matplotlib works correctly.  Tests do not exercise matplotlib.
    """
    with rasterio.open('tests/data/RGB.byte.tif') as src:
        try:
            show((src, 1), title="insert title here")
            fig = plt.gcf()
            plt.close(fig)
        except ImportError:
            pass
Exemplo n.º 12
0
def test_show_raster_title():
    """
    This test only verifies that code up to the point of plotting with
    matplotlib works correctly.  Tests do not exercise matplotlib.
    """
    with rasterio.open('tests/data/RGB.byte.tif') as src:
        try:
            show((src, 1), title="insert title here")
            fig = plt.gcf()
            plt.close(fig)
        except ImportError:
            pass
Exemplo n.º 13
0
    def print_screen(self):
        """
        This function create matplotlib image graphic and also print area of water.
        """
        print('{:.2f} km²'.format(self.calc_area()))

        fig, ax = plt.subplots(1, figsize=(12, 12))
        plt.ticklabel_format(style='plain')
        plt.title(f'{self.path}  ({rasterio.open(self.path).crs})')
        show(rasterio.open(self.path).read(1),
             cmap='gray',
             transform=rasterio.open(self.path).transform)
        plt.show()
Exemplo n.º 14
0
def test_show_raster_ax():
    """
    This test only verifies that code up to the point of plotting with
    matplotlib works correctly.  Tests do not exercise matplotlib.
    """
    with rasterio.open('tests/data/RGB.byte.tif') as src:
        try:
            fig, ax = plt.subplots(1)
            show((src, 1), ax=ax)
            fig = plt.gcf()
            plt.close(fig)
        except ImportError:
            pass
Exemplo n.º 15
0
def test_show_raster_no_bounds():
    """
    This test only verifies that code up to the point of plotting with
    matplotlib works correctly.  Tests do not exercise matplotlib.
    """
    matplotlib = pytest.importorskip('matplotlib')
    with rasterio.open('tests/data/RGB.byte.tif') as src:
        try:
            show((src, 1), with_bounds=False)
            fig = plt.gcf()
            plt.close(fig)
        except ImportError:
            pass
Exemplo n.º 16
0
def test_show_raster_ax():
    """
    This test only verifies that code up to the point of plotting with
    matplotlib works correctly.  Tests do not exercise matplotlib.
    """
    with rasterio.open('tests/data/RGB.byte.tif') as src:
        try:
            fig, ax = plt.subplots(1)
            show((src, 1), ax=ax)
            fig = plt.gcf()
            plt.close(fig)
        except ImportError:
            pass
Exemplo n.º 17
0
def test_show_raster_no_bounds():
    """
    This test only verifies that code up to the point of plotting with
    matplotlib works correctly.  Tests do not exercise matplotlib.
    """
    matplotlib = pytest.importorskip('matplotlib')
    with rasterio.open('tests/data/RGB.byte.tif') as src:
        try:
            show((src, 1), with_bounds=False)
            fig = plt.gcf()
            plt.close(fig)
        except ImportError:
            pass
Exemplo n.º 18
0
def get_color_pic(city, dataset, r, x, y, h, w, now):

    b = r[0]
    print('image:' + str(b))

    with rasterio.open(city + '\\' + dataset + b + '.jp2',
                       driver='JP2OpenJPEG') as src0:
        data0 = src0.read()
        img0 = data0[0][y:y + h, x:x + w]
    b = r[1]
    print('image:' + str(b))
    with rasterio.open(city + '\\' + dataset + b + '.jp2',
                       driver='JP2OpenJPEG') as src1:
        data1 = src1.read()
        img1 = data1[0][y:y + h, x:x + w]
    b = r[2]
    print('image:' + str(b))
    with rasterio.open(city + '\\' + dataset + b + '.jp2',
                       driver='JP2OpenJPEG') as src2:
        data2 = src2.read()
        img2 = data2[0][y:y + h, x:x + w]

    # Set image file name
    listToStr = ' '.join(map(str, r))
    imagefile = 'images/x-' + city + '_bandnum_' + listToStr + '_' + now + '_color'

    trueColor = rasterio.open(imagefile + '.tiff',
                              'w',
                              driver='Gtiff',
                              width=w,
                              height=h,
                              count=3,
                              crs=src2.crs,
                              transform=src2.transform,
                              dtype=src2.dtypes[0])
    trueColor.write(img0, 3)  # blue
    trueColor.write(img1, 2)  # green
    trueColor.write(img2, 1)  # red
    trueColor.close()

    scale = '-scale 0 255 0 25'
    options_list = ['-ot Byte', '-of JPEG', scale]
    options_string = " ".join(options_list)

    gdal.Translate(imagefile + '.jpg',
                   imagefile + '.tiff',
                   options=options_string)

    src = rasterio.open(imagefile + '.jpg')
    plot.show(src)
    '''
Exemplo n.º 19
0
def createimage(taskid, producttitle, dat):
    PRODUCT_DIR = os.path.join(config["rootdirectory"], "tasks", str(taskid),
                               str(producttitle))
    feature = read_geojson(
        os.path.join(config["rootdirectory"], "tasks", str(taskid),
                     "roi.geojson"))

    geom = geopandas.GeoDataFrame.from_features(FeatureCollection([feature]))
    geom.crs = fiona.crs.from_epsg(4326)

    for root, dir_names, file_names in os.walk(
            os.path.join(config["rootdirectory"], "tasks", str(taskid),
                         producttitle)):
        sorted_files = sorted(fnmatch.filter(file_names, "*.jp2"))
        filename = fnmatch.filter(
            file_names, "*" + feature["properties"]["band"] + "_10m.jp2")
        if len(filename) == 0:
            continue
        with rasterio.open(os.path.join(root, filename[0])) as band:
            projected_geom = geom.to_crs(band.crs)

            roi_bb = create_bb_data_frame(projected_geom.bounds.minx,
                                          projected_geom.bounds.miny,
                                          projected_geom.bounds.maxx,
                                          projected_geom.bounds.maxy)

            roi_bb_polygons = list(
                map(
                    lambda item: json.loads(
                        geopandas.GeoSeries(item).to_json())["features"][0][
                            "geometry"], roi_bb.geometry))

            bb_mask, bb_transform = mask.mask(band, roi_bb_polygons, crop=True)
            plot.show(bb_mask)

            profile = band.meta.copy()
            profile.update({
                "driver": "GTIFF",
                "dtype": bb_mask.dtype,
                "height": bb_mask.shape[1],
                "width": bb_mask.shape[2],
                "transform": bb_transform
            })
            img_name = "image" + str(
                (database.getImageCounter(taskid) + 1)) + ".tif"
            img_file = os.path.join(config["rootdirectory"], "tasks",
                                    str(taskid), img_name)
            with rasterio.open(img_file, "w", **profile) as dst:
                dst.write(bb_mask)
            database.registerNewImage(taskid, img_name, dat)
Exemplo n.º 20
0
def test_show_contour_mplargs():
    """
    This test only verifies that code up to the point of plotting with
    matplotlib works correctly.  Tests do not exercise matplotlib.
    """
    with rasterio.open('tests/data/RGB.byte.tif') as src:
        try:
            show((src, 1), contour=True, 
                levels=[25, 125], colors=['white', 'red'], linewidths=4,
                contour_label_kws=dict(fontsize=18, fmt="%1.0f", inline_spacing=15, use_clabeltext=True))
            fig = plt.gcf()
            plt.close(fig)
        except ImportError:
            pass
def image_display_sentinel():
    """
    Displays the images of landsat indices in a folder one at a time
    """
    ndmi = open('ndmi_sentinel.tiff')
    ndvi = open('ndvi_sentinel.tiff')
    savi = open('savi_sentinel.tiff')
    msavi = open('msavi_sentinel.tiff')
    ndwi = open('ndwi_sentinel.tiff')
    show(ndmi, cmap='Blues')
    show(ndvi, cmap='Greens')
    show(savi, cmap='Greens')
    show(msavi, cmap='Greens')
    show(ndwi, cmap='BrBG')
Exemplo n.º 22
0
def plot_s2_rbg_image(file_path: str, **kwargs):

    # open image with rasterio
    with rasterio.open(file_path) as src:

        # read image
        image = src.read()
        # convert to RBG Image
        rgb = np.clip(image[(3, 2, 1), ...] / 3000., 0, 1)

        # plot image
        rasterioplt.show(rgb, transform=src.transform, **kwargs)

    return None
Exemplo n.º 23
0
def write_ndwi(image_file):
    np.seterr(divide='ignore', invalid='ignore')
    p_img, p_meta = raster.load_image(image_file)

    green = p_img.read(2)
    nir = p_img.read(4)
    array = p_img.read()
    ndwi = (green - nir) / (nir + green)
    show(ndwi)
    p_meta.update({"count": p_img.count + 1})
    out_img = np.concatenate((array, np.expand_dims(ndwi, axis=0)))

    with rasterio.open(image_file, 'w', **p_meta) as outds:
        outds.write(out_img)
Exemplo n.º 24
0
def project_year(model, model_dir, what, scenario, year):
    print("projecting %s for %d using %s" % (what, year, scenario))

    models = select_models(model, model_dir)
    # Read Sam's abundance model (forested and non-forested)
    mod = modelr.load(models[0])
    predicts.predictify(mod)

    # Import standard PREDICTS rasters
    by_age = 'young_secondary' in mod.syms
    print('by_age: %s' % str(by_age))
    rasters = predicts.rasterset('luh5', scenario, year, by_age)
    rs = RasterSet(rasters)

    if what == 'bii':
        vname = 'bii'
        rs[vname] = SimpleExpr(vname, '%s / %f' % (mod.output, intercept))
    else:
        vname = mod.output
    rs[vname] = mod

    if what not in rs:
        print('%s not in rasterset' % what)
        print(', '.join(sorted(rs.keys())))
        sys.exit(1)

    stime = time.time()
    data, meta = rs.eval(what, quiet=False)
    etime = time.time()
    print("executed in %6.2fs" % (etime - stime))
    oname = os.path.join(os.environ['OUTDIR'],
                         'luh5/%s-%s-%d.tif' % (scenario, what, year))
    #hpd, _ = rs.eval('hpd', quiet=False)
    #hpd_max, meta2 = rs.eval('hpd_max', quiet=False)
    with rasterio.open(oname, 'w', **meta) as dst:
        #bb = dst.bounds
        #ul = map(int, ~meta2['affine'] * (bb[0], bb[3]))
        #lr = map(int, ~meta2['affine'] * (bb[2], bb[1]))
        #cap = ma.where(hpd > hpd_max[ul[1]:lr[1], ul[0]:lr[0]], True, False)
        #show(hpd, norm=colors.PowerNorm(gamma=0.2))
        #show(cap * 1)
        #data.mask = np.logical_or(data.mask, cap)
        dst.write(data.filled(meta['nodata']), indexes=1)
    if None:
        fig = plt.figure(figsize=(8, 6))
        ax = plt.gca()
        show(data, cmap='viridis', ax=ax)
        plt.savefig('luh2-%s-%d.png' % (scenario, year))
    return
Exemplo n.º 25
0
def write_vari(image_file):
    np.seterr(divide='ignore', invalid='ignore')
    p_img, p_meta = raster.load_image(image_file)

    red = p_img.read(1)
    green = p_img.read(2)
    blue = p_img.read(3)
    array = p_img.read()
    vari = (green - red) / (green + red - blue)
    show(vari)
    p_meta.update({"count": p_img.count + 1})
    out_img = np.concatenate((array, np.expand_dims(vari, axis=0)))

    with rasterio.open(image_file, 'w', **p_meta) as outds:
        outds.write(out_img)
Exemplo n.º 26
0
def test_show_contour_mplargs():
    """
    This test only verifies that code up to the point of plotting with
    matplotlib works correctly.  Tests do not exercise matplotlib.
    """
    matplotlib = pytest.importorskip('matplotlib')
    with rasterio.open('tests/data/RGB.byte.tif') as src:
        try:
            show((src, 1), contour=True,
                levels=[25, 125], colors=['white', 'red'], linewidths=4,
                contour_label_kws=dict(fontsize=18, fmt="%1.0f", inline_spacing=15, use_clabeltext=True))
            fig = plt.gcf()
            plt.close(fig)
        except ImportError:
            pass
Exemplo n.º 27
0
def plot_highest_value_cell(filename):
    """This function outputs the geographic coordinates of the cell with the
        highest value in the dataset, and output a visualization of the
        raster with the cell highlighted."""
    try:
        with rasterio.open(filename, 'r') as src:
            if src.count != 1:
                raise ValueError
            else:
                band = src.read(1)
                max_value = band.max()
                width = src.width
                height = src.height
                heightest_cell = []
                coordinate = []
                for col in range(width):
                    for row in range(height):
                        if band[row, col] == max_value:
                            heightest_cell.append((row, col))
                for cell in heightest_cell:
                    x_centre, y_centre = src.xy(cell[0], cell[1])
                    coordinate.append((x_centre, y_centre))

                fig, ax1 = plt.subplots(1, figsize=(9, 5))
                plot.show((src, 1), interpolation='none', ax=ax1)
                ax1.set_title('Figure 1. Visualization of CLIP.tif',
                              fontsize=18)
                ax1.set_xlabel('Longitude', fontsize=14)
                ax1.set_ylabel('Latitude', fontsize=14)

                for cell in coordinate:
                    lat, lon = cell
                    ax1.plot([lat], [lon], 'ro')
                    text = ('Cell with highest value\n' + '(' + '%.5f' % lat +
                            ',' + '%.5f' % lon + ')')
                    ax1.annotate(text,
                                 xy=cell,
                                 fontsize=13,
                                 color='r',
                                 xytext=(lat - 0.2, lon + 0.1),
                                 arrowprops=dict(facecolor='black',
                                                 shrink=0.1))
                plt.show()
        return coordinate
    except ValueError:
        print('Band of input dataset over 1.')
    except rasterio.errors.RasterioIOError as reason:
        print('Wrong input file: ' + str(reason))
def exclusion_layers(path_to_shapes, path_to_land_cover, path_to_slope,
                     path_to_protected_areas, path_to_settlements,
                     path_to_output, country_code):
    """Visualise the exclusion layers defining land eligibility."""
    with fiona.open(path_to_shapes, "r") as shapefile:
        shape = [
            feature["geometry"] for feature in shapefile
            if feature["properties"]["country_code"] == country_code
        ][0]
    x_min, y_min, x_max, y_max = shapely.geometry.asShape(shape).bounds
    land_cover, slope, protected_areas, esm = _read_raster(
        x_min, y_min, x_max, y_max, path_to_land_cover, path_to_slope,
        path_to_protected_areas, path_to_settlements)
    fig = plt.figure(figsize=(10, 5.5), frameon=True, constrained_layout=True)
    ax1 = fig.add_subplot(221)
    show(land_cover,
         extent=(x_min, x_max, y_min, y_max),
         ax=ax1,
         cmap=ListedColormap(
             sns.light_palette(sns.desaturate(BLUE, 0.85)).as_hex()))
    ax1.set_title("Exclusion from land cover")
    ax2 = fig.add_subplot(222)
    show(slope,
         extent=(x_min, x_max, y_min, y_max),
         ax=ax2,
         cmap=ListedColormap(
             sns.light_palette(sns.desaturate(YELLOW, 0.85)).as_hex()))
    ax2.set_title("Exclusion from slope")
    ax3 = fig.add_subplot(223)
    show(protected_areas,
         extent=(x_min, x_max, y_min, y_max),
         ax=ax3,
         cmap=ListedColormap(
             sns.light_palette(sns.desaturate(GREEN, 0.85)).as_hex()))
    ax3.set_title("Exclusion from protected areas")
    ax4 = fig.add_subplot(224)
    show(esm,
         extent=(x_min, x_max, y_min, y_max),
         ax=ax4,
         cmap=ListedColormap(
             sns.light_palette(sns.desaturate(RED, 0.85)).as_hex()))
    ax4.set_title("Exclusion from urban settlements")
    for ax in [ax1, ax2, ax3, ax4]:
        ax.add_patch(_inverted_shape(shape))
        ax.set_xticks([])
        ax.set_yticks([])
        ax.spines["top"].set_visible(False)
        ax.spines["right"].set_visible(False)
        ax.spines["bottom"].set_visible(False)
        ax.spines["left"].set_visible(False)
    fig.set_constrained_layout_pads(hspace=0.1, wspace=0.1)
    if path_to_output[-3:] == "png":
        fig.savefig(path_to_output, dpi=600, transparent=False)
    else:
        fig.savefig(path_to_output,
                    dpi=600,
                    transparent=False,
                    pil_kwargs={"compression": "tiff_lzw"})
Exemplo n.º 29
0
def show_img(path, show_vill=False):

    if show_vill != False:

        raster = rasterio.open(path)
        switcher = {
            'NW':
            rasterio.open(
                'H:/sentinel2/Ghana/Validation/NW_coord.tif').transform,
            'SE':
            rasterio.open(
                'H:/sentinel2/Ghana/Validation/SE_coord.tif').transform
        }
        af = switcher[show_vill]
        fig, ax = plt.subplots(1, figsize=(50, 50))
        img = show(raster.read(), transform=af, ax=ax)
        vill = ax.scatter(village_1['POINT_X'],
                          village_1['POINT_Y'],
                          color='red',
                          marker='x')
        plt.tick_params(axis='x', which='major', labelsize=30)
        plt.tick_params(axis='y', which='major', labelsize=30)
        plt.show()
    else:
        img = mpimg.imread(path)
        plt.figure(figsize=(50, 50))
        plt.imshow(img)
Exemplo n.º 30
0
def plot_ndarray(arr,
                 transform=None,
                 cmap=None,
                 legend=False,
                 figsize=None,
                 ax=None,
                 **show_kws):
    if cmap is None:
        cmap = plt.get_cmap('terrain')

    if ax is None:
        fig, ax = plt.subplots(figsize=figsize)
    ax.set_aspect('equal')

    ax = show(arr, ax=ax, transform=transform, cmap=cmap, **show_kws)

    if legend:
        im = ax.get_images()[0]
        for class_val in np.unique(arr.ravel()):
            ax.plot(ax.get_xlim()[0],
                    ax.get_ylim()[0],
                    'o',
                    c=cmap(im.norm(class_val)),
                    label=class_val)

        ax.legend()

    return ax
Exemplo n.º 31
0
def plotHeatmap(
        year=2045,
        data="jobs",
        dataName='Employment',
        method='Kernel',
        cellSize=100,
        searchRadius=1000,
        colormap='Reds',
        export=False,
        outpath=r"C:\Users\clid1852\OneDrive - lanecouncilofgovernments\UrbanSim\maps\heatmap",
        changeFileNm=False):
    fileName = method + data + str(year)[2:4] + "_" + str(
        cellSize) + "_" + str(searchRadius)
    file = os.path.join(path, fileName + ".tif")
    src = rasterio.open(file)
    fig, ax = plt.subplots(1, figsize=(28, 24))
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("bottom", size="5%", pad="2%")
    data = src.read(1)
    ndata = np.where(data == data.min(), np.nan, data)
    data_ex = data[data != data.min()]
    image = show(ndata, transform=src.transform, ax=ax, cmap=colormap)
    MPObd.plot(ax=ax, facecolor="none", edgecolor="black", linestyle='--')
    ctx.add_basemap(ax, source=ctx.providers.Stamen.TonerLite, alpha=0.3)

    if method == 'Kernel':
        ax.set_title(dataName + " " + method + " Heatmap in " + str(year) +
                     " Size: " + str(cellSize) + " Radius: " +
                     str(searchRadius),
                     fontsize=50,
                     fontname="Palatino Linotype",
                     color="grey",
                     loc='center')
    else:
        ax.set_title(dataName + " " + method + " Heatmap in " + str(year) +
                     " Size: " + str(cellSize),
                     fontsize=50,
                     fontname="Palatino Linotype",
                     color="grey",
                     loc='center')

    image_hidden = ax.imshow(ndata, cmap=colormap)
    fmt = mpl.ticker.ScalarFormatter(useMathText=True)
    fmt.set_powerlimits((0, 0))
    cbar = plt.colorbar(image_hidden,
                        format=fmt,
                        ax=ax,
                        cax=cax,
                        orientation="horizontal")
    mpl.rcParams.update({'font.size': 20})
    ax.axis("off")
    if export:
        if changeFileNm:
            fileName = fileName + "_" + colormap
        imageName = fileName + ".png"
        plt.savefig(os.path.join(outpath, imageName),
                    transparent=True,
                    bbox_inches='tight')
        print("Saved image " + imageName + "...")
    src.close()
Exemplo n.º 32
0
def bgr(self,
        index,
        blu=None,
        gre=None,
        red=None,
        b_thresh=False,
        g_thresh=False,
        r_thresh=False,
        figsize=(10, 10),
        array=True):
    #export false color image
    if b_thresh:
        blu = np.where((b_thresh[0] < blu) & (blu < b_thresh[1]), blu, 0)
    if g_thresh:
        gre = np.where((g_thresh[0] < gre) & (gre < g_thresh[1]), gre, 0)
    if r_thresh:
        red = np.where((r_thresh[0] < red) & (red < r_thresh[1]), red, 0)

    bgr = rio.open('./{}/'.format(self.name) + '{}.tiff'.format(index),
                   'w',
                   driver='Gtiff',
                   width=self.meta["width"],
                   height=self.meta["height"],
                   count=3,
                   crs=self.meta["crs"],
                   transform=self.meta["transform"],
                   dtype=self.meta["dtype"])
    bgr.write(blu[0], 3)  #Blue
    bgr.write(gre[0], 2)  #Green
    bgr.write(red[0], 1)  #Red
    bgr.close()
    bgr_assemble = rio.open('./{}/'.format(self.name) +
                            '{}.tiff'.format(index),
                            count=3)
    fig = plt.figure(figsize=figsize)
    plt.title(str(index))
    show(bgr_assemble)
    rio.plot.show_hist(bgr_assemble,
                       bins=50,
                       lw=0.0,
                       stacked=False,
                       alpha=0.8,
                       histtype='stepfilled',
                       title="Histogram")

    if array:
        return bgr_assemble.read(1)
Exemplo n.º 33
0
    def ExtractParametersBoundaries(Basin):
        """
        =====================================================
            ExtractParametersBoundaries(Basin)
        =====================================================

        Parameters
        ----------
        Basin : [Geodataframe]
            gepdataframe of catchment polygon, make sure that the geodataframe contains
            one row only, if not merge all the polygons in the shapefile first.

        Returns
        -------
        UB : [list]
            list of the upper bound of the parameters.
        LB : [list]
            list of the lower bound of the parameters.

        the parameters are
            ["tt", "sfcf","cfmax","cwh","cfr","fc","beta",
             "lp","k0","k1","k2","uzl","perc", "maxbas"]
        """
        ParametersPath = os.path.dirname(Hapi.__file__)
        ParametersPath = ParametersPath + "/Parameters"
        ParamList = ["01_tt", "02_rfcf","03_sfcf","04_cfmax","05_cwh","06_cfr",
                     "07_fc","08_beta","09_etf","10_lp","11_k0","12_k1","13_k2",
                     "14_uzl","15_perc", "16_maxbas","17_K_muskingum",
                     "18_x_muskingum"]

        raster = rasterio.open(ParametersPath + "/max/" + ParamList[0] + ".tif")
        Basin = Basin.to_crs(crs=raster.crs)
        # max values
        UB = list()
        for i in range(len(ParamList)):
            raster = rasterio.open(ParametersPath + "/max/" + ParamList[i] + ".tif")
            array = raster.read(1)
            affine = raster.transform
            UB.append(zonal_stats(Basin, array, affine=affine, stats=['max'])[0]['max']) #stats=['min', 'max', 'mean', 'median', 'majority']

        # min values
        LB = list()
        for i in range(len(ParamList)):
            raster = rasterio.open(ParametersPath + "/min/" + ParamList[i] + ".tif")
            array = raster.read(1)
            affine = raster.transform
            LB.append(zonal_stats(Basin, array, affine=affine, stats=['min'])[0]['min'])

        Par = pd.DataFrame(index = ParamList)

        Par['UB'] = UB
        Par['LB'] = LB
        # plot the given basin with the parameters raster
        ax = show((raster, 1), with_bounds=True)
        Basin.plot(facecolor='None', edgecolor='blue', linewidth=2, ax=ax)
        # ax.set_xbound([Basin.bounds.loc[0,'minx']-10,Basin.bounds.loc[0,'maxx']+10])
        # ax.set_ybound([Basin.bounds.loc[0,'miny']-1, Basin.bounds.loc[0,'maxy']+1])

        return Par
Exemplo n.º 34
0
def ARVI():  # currently not working
    '''
    Atmospherically Resistant Vegetation Index
    '''
    arvi = ((band5 - ((band4) * (band2))) / (band5 - (band4 + band2)))
    plot.show(arvi)
    new_arvi = rasterio.open(path + '\\arvi.tif',
                             'w',
                             driver='Gtiff',
                             height=height,
                             width=width,
                             count=1,
                             dtype='float64',
                             crs=crs,
                             transform=affine)
    new_arvi.write(arvi, 1)
    new_arvi.close()
Exemplo n.º 35
0
def plotRaster(yrbuilt = 2021, field = "njobs", fieldName = 'Employment', colormap = 'coolwarm', 
                cellSize = 25, searchRadius = 1000, export = True, changeFileNm = False):
    
    if changeFileNm:
        file = os.path.join(path, 'output', 
                            "KernelD_" + field + "_" + str(yrbuilt) + "_" + str(cellSize) + "_" + str(searchRadius) + ".tif")
    else:
        if yrbuilt == "":
            file = os.path.join(path, 'output', "KernelD_" + field + ".tif")
        else:
            file = os.path.join(path, 'output', "KernelD_" + field + "_" + str(yrbuilt) + ".tif")
    
    src = rasterio.open(file)
    fig, ax = plt.subplots(figsize=(28, 24))
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("bottom", size="5%", pad="2%")
    
    # plot on the same axis with rio.plot.show
    data = src.read(1)
    ndata = np.where(data == data.min(), np.nan, data)

    data_ex = data[data != data.min()]
    norm = mpl.colors.TwoSlopeNorm(vmin=getMinMax(field)[0], vcenter=0, vmax=getMinMax(field)[1])

    image = show(ndata, 
                 transform=src.transform, 
                 ax=ax, 
                 cmap=colormap, 
                 norm=norm)

    MPObd.plot(ax=ax, facecolor="none", edgecolor="black", linestyle='--')
    
    ctx.add_basemap(ax, source=ctx.providers.Stamen.TonerLite, alpha=0.3)
    if yrbuilt == "":
        ax.set_title(fieldName + " Heatmap in Central Lane MPO in 2045", fontsize=50, fontname="Palatino Linotype", 
                  color="grey", loc = 'center')
    else:
        ax.set_title("Growth in {0} in Central Lane MPO by {1}".format(fieldName, str(yrbuilt)), 
                     fontsize=50, fontname="Palatino Linotype", color="grey", loc = 'center')
    
    image_hidden = ax.imshow(ndata, 
                             cmap=colormap, 
                             norm=norm)

    fmt = mpl.ticker.ScalarFormatter(useMathText=True)
    #fmt = ScalarFormatterForceFormat()
    fmt.set_powerlimits((0, 0))
    cbar = plt.colorbar(image_hidden, format=fmt, ax=ax, cax=cax, orientation="horizontal")
    ax.axis("off");
    
    if export:
        if yrbuilt == "":
            plt.savefig(os.path.join(outpath, "heatmap_" + field + ".png"), transparent=True, bbox_inches='tight')
            print("Saved image for " + field + "...")
        else:
            plt.savefig(os.path.join(outpath, "heatmap_" + field + "_" + str(yrbuilt) + ".png"), transparent=True, bbox_inches='tight')
            print("Saved image for {0} in {1}...".format(field, str(yrbuilt)))
    src.close()
Exemplo n.º 36
0
    def plot_quicklooks(self,
                        figsize: Tuple[int, int] = (8, 8),
                        filepaths: List = None) -> None:
        """
        Plots the downloaded quicklooks (filepaths saved to self.quicklooks of the
        respective object, e.g. job, catalog).

        Args:
            figsize: matplotlib figure size.
        """
        if is_notebook():
            get_ipython().run_line_magic("matplotlib", "inline")

        # TODO: Remove empty axes & give title option.
        if filepaths is None:
            if self.quicklooks is None:
                raise ValueError(
                    "You first need to download the quicklooks via .download_quicklooks()."
                )
            filepaths = self.quicklooks

        if len(filepaths) < 2:
            nrows, ncols = 1, 1
        else:
            ncols = 2
            nrows = int(math.ceil(len(filepaths) / float(ncols)))

        warnings.filterwarnings(
            "ignore", category=rasterio.errors.NotGeoreferencedWarning)

        fig, axs = plt.subplots(nrows=nrows, ncols=ncols, figsize=figsize)
        if len(filepaths) > 1:
            axs = axs.ravel()
        else:
            axs = [axs]
        for idx, fp in enumerate(filepaths):
            with rasterio.open(fp) as src:
                show(
                    src.read(),
                    transform=src.transform,
                    title=Path(fp).stem,
                    ax=axs[idx],
                )
        plt.tight_layout()
        plt.show()
Exemplo n.º 37
0
def plot_poly(multi_polygon,img):
    
    mp=MultiPolygon([feature for feature in multi_polygon])
    patches=[PolygonPatch(feature, edgecolor="#FFFFFF", facecolor="#555555", linewidth=2) 
            for feature in multi_polygon]

    fig,ax = plt.subplots(figsize=(10,10))

    cm = plt.get_cmap('RdBu')
    num_colours = len(mp)
    
    minx, miny, maxx, maxy = mp.bounds
    print(mp.bounds)
    w, h = maxx - minx, maxy - miny
    ax.set_ylim(maxy + 0.1 * h, miny - 0.1 * h)
    ax.set_xlim(minx - 0.1 * w, maxx + 0.1 * w)
    
    ax.set_aspect(1)

    patches = []
    for idx, p in enumerate(mp):
        colour = cm(1. * idx / num_colours)
        patches.append(PolygonPatch(p, fc=colour, ec='red', alpha=0.65, zorder=1))


    ax.add_collection(PatchCollection(patches, match_original=True))
    ax.set_axis_on()
    ax.set_xticks(np.around(np.arange(minx - 0.1 * w, maxx + 0.1 * w, 30),0))
    ax.set_yticks(np.around(np.arange( miny - 0.1 * h ,maxy + 0.1 * h, 30),0))
    ax.tick_params('both',pad=15)
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.xaxis.label.set_color('white')
    ax.yaxis.label.set_color('white')
    plt.xticks(rotation=45,horizontalalignment='right')
    ax.grid(b=True, which='major', color='w', linewidth=0.8)
    #ax.grid(b=True, which='minor', color='w', linewidth=0.5)
    #ax.get_xaxis().set_minor_locator(mpl.ticker.AutoMinorLocator())
    #ax.get_yaxis().set_minor_locator(mpl.ticker.AutoMinorLocator())
    ax.tick_params(axis='x', colors='white')
    ax.tick_params(axis='y', colors='white')
    plt.title("Shapefile",color='#FFFFFF')
    show(img,ax, cmap='RdYlGn')
    #plt.savefig('Field_Plot.png', alpha=True, dpi=300)
    plt.show()
Exemplo n.º 38
0
def show_max_probas(dwm,hmm,years, cmap=cmocean.cm.rain):
    """
    Function to plot max probability across bands for each year

    Args:
        dwm (dict): Dynamic World Model outputs, with year ints as keys and rasterio dataset pointers as values
        hmm (dict): Hidden Markov Model outputs, with year ints as keys and rasterio dataset pointers as values
        years (list): years to loop through for calculating annual change
        cmap (cmap): colormap

    Returns:
        Plots max probability per cell for each year
    """
    fig, axs = plt.subplots(len(years),2,figsize=(2*4,len(years)*4))
    for i,x in enumerate(years):
        show(dwm[f'{x}'].read().max(axis=0), ax=axs[i,0], cmap=cmap, vmin=0, vmax=1,title=x)
        show(hmm[f'{x}'].read().max(axis=0), ax=axs[i,1], cmap=cmap, vmin=0, vmax=1,title=x)
    return plt.show()
Exemplo n.º 39
0
def test_show_cmyk_interp(tmpdir):
    """A CMYK TIFF has cyan, magenta, yellow, black bands."""
    with rasterio.open('tests/data/RGB.byte.tif') as src:
        meta = src.meta
    meta['photometric'] = 'CMYK'
    meta['count'] = 4
    tiffname = str(tmpdir.join('foo.tif'))
    with rasterio.open(tiffname, 'w', **meta) as dst:
        assert dst.profile['photometric'] == 'cmyk'
        assert dst.colorinterp(1) == ColorInterp.cyan
        assert dst.colorinterp(2) == ColorInterp.magenta
        assert dst.colorinterp(3) == ColorInterp.yellow
        assert dst.colorinterp(4) == ColorInterp.black

    with rasterio.open(tiffname) as src:
        try:
            show(src)
            fig = plt.gcf()
            plt.close(fig)
        except ImportError:
            pass
Exemplo n.º 40
0
def test_show_cmyk_interp(tmpdir):
    """A CMYK TIFF has cyan, magenta, yellow, black bands."""
    matplotlib = pytest.importorskip('matplotlib')
    with rasterio.open('tests/data/RGB.byte.tif') as src:
        meta = src.meta
    meta['photometric'] = 'cmyk'
    meta['count'] = 4
    tiffname = str(tmpdir.join('foo.tif'))
    with rasterio.open(tiffname, 'w', **meta) as dst:
        assert dst.colorinterp == (
            ColorInterp.cyan,
            ColorInterp.magenta,
            ColorInterp.yellow,
            ColorInterp.black)

    with rasterio.open(tiffname) as src:
        try:
            show(src)
            fig = plt.gcf()
            plt.close(fig)
        except ImportError:
            pass
Exemplo n.º 41
0
def test_plt_transform():
    matplotlib = pytest.importorskip('matplotlib')
    with rasterio.open('tests/data/RGB.byte.tif') as src:
        show(src.read(), transform=src.transform)
        show(src.read(1), transform=src.transform)
Exemplo n.º 42
0
def test_plt_transform():
    with rasterio.open('tests/data/RGB.byte.tif') as src:
        show(src.read(), transform=src.transform)
        show(src.read(1), transform=src.transform)