Beispiel #1
0
def show_tiff(filename):
    # open data source.
    with rasterio.open(filename) as ds:
        # show the data source.
        show(ds)
        # show the histogram.
        show_hist(ds, bins=50, lw=0.0, stacked=False, alpha=0.3, histtype='stepfilled', title="Histogram")
Beispiel #2
0
def get_tiff_info(filename):
    # open tiff
    with rasterio.open(filename) as ds:
        # export datatype
        print(f'数据格式:{ds.driver}')
        # export band counts
        print(f'波段数目:{ds.count}')
        # export image width
        print(f'影像宽度:{ds.width}')
        # export image height
        print(f'影像高度:{ds.height}')
        # export image boundary
        print(f'地理范围:{ds.bounds}')
        # export reflection transformation parameter
        print(f'反射变换参数(六参数模型):\n {ds.transform}')
        # export projection
        print(f'投影定义:{ds.crs}')
        # show the histogram
        show_hist(ds, bins=50, lw=0.0, stacked=False, alpha=0.3, histtype='stepfilled', title='Histogram')
        # get the bands counts
        num_bands = ds.count
        # show the image
        for index in range(num_bands):
            # define band number.
            band = index + 1
            # show the gray image.
            show((ds, band), title="band" + str(band), cmap='Greys_r')
            # show the histogram of every band.
            plt.hist(ds.read(band))
            # show the title of every band.
            plt.title("band" + str(band) + " histogram")
            # show.
            plt.show()
Beispiel #3
0
def polt_histograms(file1, file2):
    """This function outputs the histograms of input datasets."""
    try:
        fig1, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5))
        fig1.suptitle(
            'Figure 2. Visualization of Resampled dataset and Histogram',
            fontsize=18)
        fig2, (ax3, ax4) = plt.subplots(1, 2, figsize=(14, 7))
        with rasterio.open(file1, 'r') as src1:
            plot.show((src1, 1), cmap='Greys_r', interpolation='none', ax=ax1)
            ax1.set_title('Resample(2x).tif', fontsize=16)
            ax1.set_xlabel('X /metre', fontsize=12)
            ax1.set_ylabel('Y /metre', fontsize=12)

            plot.show_hist(src1, ax=ax3)
            ax3.set_title('Histogram of Resample(2x).tif', fontsize=16)
            ax3.set_xlim(0, 1600)
        with rasterio.open(file2, 'r') as src2:
            plot.show((src2, 1), cmap='Greys_r', interpolation='none', ax=ax2)
            ax2.set_title('Resample(4x).tif', fontsize=16)
            ax2.set_xlabel('X /metre', fontsize=12)
            ax2.set_ylabel('Y /metre', fontsize=12)

            plot.show_hist(src2, ax=ax4)
            ax4.set_title('Histogram of Resample(4x).tif', fontsize=16)
            ax4.set_xlim(0, 1600)

        plt.show()
    except rasterio.errors.RasterioIOError as e:
        print('Wrong input file: ' + str(e))
Beispiel #4
0
def getTIFFInfo(imagepath):
    with rasterio.open(imagepath) as ds:

        print(f'数据格式:{ds.driver}')
        print(f'波段数目:{ds.count}')
        print(f'影像宽度:{ds.width}')
        print(f'影像高度:{ds.height}')
        print(f'地理范围:{ds.bounds}')
        print(f'反射变换参数(六参数模型):\n {ds.transform}')
        print(f'投影定义:{ds.crs}')
        show_hist(ds,
                  bins=50,
                  lw=0.0,
                  stacked=False,
                  alpha=0.3,
                  histtype='stepfilled',
                  title="Histogram")
        num_bands = ds.count
        print('波段数为:' + str(num_bands))
        for index in range(num_bands):
            band = index + 1
            show((ds, band), cmap='Greys_r')
            plt.hist(ds.read(band))
            plt.title("band" + str(band))
            plt.show()
Beispiel #5
0
def showTiFF(imagepath):
    with rasterio.open(imagepath) as ds:
        show(ds)
        show_hist(ds,
                  bins=50,
                  lw=0.0,
                  stacked=False,
                  alpha=0.3,
                  histtype='stepfilled',
                  title="Histogram")
Beispiel #6
0
def test_show_hist_large():
    """
    This test only verifies that code up to the point of plotting with
    matplotlib works correctly.  Tests do not exercise matplotlib.
    """
    try:
        rand_arr = np.random.randn(10, 718, 791)
        show_hist(rand_arr)
        fig = plt.gcf()
        plt.close(fig)
    except ImportError:
        pass
Beispiel #7
0
def test_show_hist_large():
    """
    This test only verifies that code up to the point of plotting with
    matplotlib works correctly.  Tests do not exercise matplotlib.
    """
    try:
        rand_arr = np.random.randn(10, 718, 791)
        show_hist(rand_arr)
        fig = plt.gcf()
        plt.close(fig)
    except ImportError:
        pass
Beispiel #8
0
    def histogram(self, ax=None, **kwargs):
        """
        Method to plot a histogram of digital numbers

        Parameters
        ----------
        ax : matplotlib.pyplot.axes
            optional matplotlib axes for plotting

        **kwargs :
            matplotlib keyword arguments
            see matplotlib documentation for valid
            arguments for histogram

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

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

        if "alpha" not in kwargs:
            kwargs["alpha"] = 0.3

        if self._dataset is not None:
            ax = show_hist(self._dataset, ax=ax, **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_hist(data, ax=ax, **kwargs)

        return ax
Beispiel #9
0
def get_histogram(document_id):
    raster = read_document(document_id)
    plt.show = lambda: None

    show_hist(raster,
              title='Histogram',
              histtype='stepfilled',
              bins=50,
              lw=0.0,
              stacked=False,
              alpha=0.3)

    return get_image_from_plot()
Beispiel #10
0
def test_show_hist_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_hist(src, bins=50, lw=0.0, stacked=False, alpha=0.3, 
               histtype='stepfilled', title="World Histogram overlaid")
            fig = plt.gcf()
            plt.close(fig)
        except ImportError:
            pass
Beispiel #11
0
def raster_histogram(input, varname):
    """Create raster histograms each band in a raster and save them to file"""
    
    # Read the data
    raster = rasterio.open(input)

    for i in raster.indexes:
        fig, ax = plt.subplots(1)
        # TODO: Make this calculation automatic based on SD or something
        ax.set_xlim([-0.5, 0.5])
        show_hist(raster.read(i, masked=True), bins=50, lw=2, masked=True, alpha=0.6,
                  title="Histogram - band{}".format(i), ax=ax, facecolor='blue')
        plt.xlabel(varname)
        fig.savefig(varname + "_hist_band{}".format(i), dpi=300, bbox_inches='tight')
Beispiel #12
0
def test_show_hist_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_hist(src, bins=50, lw=0.0, stacked=False, alpha=0.3,
               histtype='stepfilled', title="World Histogram overlaid")
            fig = plt.gcf()
            plt.close(fig)
        except ImportError:
            pass
Beispiel #13
0
def image_histogram(ndwi2):
    from rasterio.plot import show_hist
    co, ce =show_hist(ndwi)
    fig = plt.figure(figsize=(10,7))
    fig.set_facecolor('yellow')
    plt.plot(ce[1::], co[1::])
    plt.show()
def calculate_ndwi(rasterfile, outfile=None, plot=False):
    raster_filepath = os.path.dirname(rasterfile) + "/"
    raster_filename = os.path.basename(rasterfile)

    img = raster_filepath + raster_filename

    print("Opening", raster_filename, "to read in band data:", end=" ")
    with rasterio.open(img, driver="GTiff") as src:
        kwargs = src.meta
        kwargs.update(dtype=rasterio.float32, count=1)

        nir_num = src.count  # adjusting NIR band to 4 or 5 band images

        green_band = src.read(2).astype(rasterio.float32)  # band 2 - green
        nir_band = src.read(nir_num).astype(rasterio.float32)  # band 4 - NIR
        print("DONE\n")

    print("Calculating NDWI:", end=" ")
    np.seterr(divide='ignore', invalid='ignore')
    ndwi = (green_band - nir_band) / (green_band + nir_band)
    print("DONE\n")
    ndwi = cv2.GaussianBlur(ndwi, (17, 17), 0)
    if outfile:
        out_filename = outfile
    else:
        out_filename = raster_filepath + raster_filename.split(
            sep=".")[0] + "_NDWI.tif"
    print("Saving calculated NDWI image as", out_filename, ":", end=" ")
    with rasterio.open(out_filename, 'w', **kwargs) as dst:
        dst.nodata = 0
        dst.write_band(1, ndwi.astype(rasterio.float32))
        print("DONE\n")

    if plot:
        bands = [ndwi]
        labels = ["NDWI (Normalized Difference Water Index)"]
        plot_raster(bands, labels)

        show_hist(ndwi,
                  bins=100,
                  stacked=False,
                  alpha=0.3,
                  histtype='stepfilled',
                  title="NDWI Values")
    return out_filename
Beispiel #15
0
def make_nice_single_raster_plot(input_raster, no_of_histg_bins):
    fig, (ax1, ax2, ax3) = pyplot.subplots(1, 3, figsize=(21, 7))
    show(input_raster.read(),
         ax=ax1,
         transform=input_raster.transform,
         cmap='BrBG',
         title='#NoRainbow')
    show(input_raster.read(),
         ax=ax2,
         transform=input_raster.transform,
         contour=True,
         title='contours')
    show_hist(input_raster,
              bins=no_of_histg_bins,
              lw=0.0,
              stacked=False,
              histtype='stepfilled',
              title="Histogram of height vals")
Beispiel #16
0
def test_show_hist():
    """
    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_hist((src, 1), bins=256)
            fig = plt.gcf()
            plt.close(fig)
        except ImportError:
            pass

        try:
            show_hist(src.read(), bins=256)
            fig = plt.gcf()
            plt.close(fig)
        except ImportError:
            pass
Beispiel #17
0
def test_show_hist():
    """
    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_hist((src, 1), bins=256)
            fig = plt.gcf()
            plt.close(fig)
        except ImportError:
            pass

        try:
            show_hist(src.read(), bins=256)
            fig = plt.gcf()
            plt.close(fig)
        except ImportError:
            pass
Beispiel #18
0
    def display_img(self, path):

        ## matplob
        #im = plt.imshow(b)
        #plt.colorbar(im)
        #plt.show()

        ## rasterio
        src = rasterio.open(path + "/htAccumulation.tif")
        plt.imshow(src.read(1), cmap='pink')

        plt.show()

        show_hist(src,
                  bins=50,
                  lw=0.0,
                  stacked=False,
                  alpha=0.3,
                  histtype='stepfilled',
                  title="Histogram")
Beispiel #19
0
def png_hist(img_pth, no):
    fold_loc, title = split(img_pth)
    save_name = title[:-4]
    img_type = save_name.split("_")
    img_type = img_type[-1]

    # Determine bins
    bins = np.arange(no + 2) - 0.5
    # Open raster
    with rasterio.open(img_pth) as src:
        fig, (ax1) = plt.subplots(1, 1, figsize=(7, 7))

        show_hist(src, bins=bins, lw=0.0, title=title, ax=ax1)

        plt.xticks(np.arange(0, no + 2, 1))
        plt.legend([img_type])
        save_pth = fold_loc + "\\" + save_name + "_hist.png"
        plt.savefig(save_pth)
        # plt.show()

    return save_pth
Beispiel #20
0
def plot_slope_distribution(slope_1, slope_2, algorithms):
    """This fuction plots the distribution of the slope values
        for the input algorithms."""
    try:
        if type(algorithms) != str:
            raise ValueError
        else:
            fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 7))
            fig.suptitle(algorithms, fontsize=18)
            plot.show_hist(slope_1, bins=50, ax=ax1)
            ax1.set_title('Slope Value Distribution of Resample(2x).tif',
                          fontsize=16)
            ax1.set_xlim(0, 90)

            plot.show_hist(slope_2, bins=50, ax=ax2)
            ax2.set_title('Slope Value Distribution of Resample(4x).tif',
                          fontsize=16)
            ax2.set_xlim(0, 90)

            plt.show()
    except ValueError:
        print('Input parameter(algorithms) must be str!')
Beispiel #21
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('source_dem', metavar='source_dem', type=str, help='source_dem path')
    parser.add_argument('factor', metavar='factor', type=int, help='dec factor')
    args = parser.parse_args()
    source_dem = args.source_dem
    factor = args.factor

    dem = source_dem.split('/')[-1]
    path = source_dem.replace(dem,'')
    output_path = path + '{}_{}.tif' 

    # Resample the source image using different resampling methods
    resample_list = ['nearest','average','bilinear','gauss','cubic','cubicspline','average_magphase','mode']
    dec_factor = str(factor)

    for resample in resample_list:
        print("gdaladdo -r "+ resample +" -ro " + source_dem + " --config COMPRESS_OVERVIEW LZW " + dec_factor)
        os.system("gdaladdo -r "+ resample +" -ro " + source_dem + " --config COMPRESS_OVERVIEW LZW " + dec_factor)
        ovr = '.ovr'
        ovr_path = r'{}{}'.format(source_dem,ovr) 
        new_path = output_path.format(resample,dec_factor)
        os.rename(ovr_path,new_path)
    
    # Read each resampled image an then:
    #  extract the information
    #  create a thumbnail and histogram
    for filename in glob.glob(os.path.join(path, '*.tif')):
        with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
            cog_sample = rasterio.open(filename)
            cur_name = os.path.basename(filename)[:-4]
    
            bound = str(cog_sample.bounds)
            crs = str(cog_sample.crs)
            dtype = str(cog_sample.dtypes[0])
            trans = str(cog_sample.transform)
            nodata = str(cog_sample.nodata)
            shape = str(cog_sample.shape)
            meta = str(cog_sample.meta)
            output = "{}_info".format(cur_name)
            f = open(output+'.txt',"w")
            f.write("stats: " + "\n" + 
                    "bound: " + bound + "\n" + 
                    "crs: " + crs + "\n" + 
                    "dtype: " + dtype + 
                    "transform: " + trans + 
                    "nodata: " + nodata + 
                    "shape: " + shape + 
                    "metadata: " + meta)
    
            fig, (aximage, axhist) = pyplot.subplots(1, 2, figsize=(49,28))
            figtitle="{} sample cog and histogram".format(cur_name)
            fig.suptitle(figtitle,fontsize=30)
            #create histogram using rasterio show histogram, pass axes subplot handle to axhist
            bins=50
            show_hist(cog_sample, bins=bins, lw=0.0, 
                    stacked=False, alpha=0.3,
                    histtype='stepfilled',
                    ax=axhist)
            axhist.set_title('')
            axhist.set_xlabel('elevation (m)')
            axhist.set_ylabel('')
            axhist.legend('')
            #create display image passing axes subplot handle to aximage
            show(cog_sample, cmap='gray',transform=cog_sample.transform, ax=aximage)
            #save the figure
            fname=path+cur_name+'.png'
            pyplot.savefig(fname,format='png')

    fields = ['Name', 'Resampling_Method', 'Overview', 'Driver', 'Data Type', 
          'crs', 'Width', 'Height', 'Nodata_Pixels', 'Pixels_with_Values',
          'Pixel_Size', 'Min', 'Max', 'Range', 'Q1', 'Q3', 'Mean', 'Median', 
          'Std', 'Var']
    rows = [fields]
    for filename in glob.glob(os.path.join(path, '*.tif')):
        with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
            cog = rasterio.open(filename)
            cur_name = os.path.basename(filename).split('_')[0]
            resampling = os.path.basename(filename)[:-7]
            overview = 32

            # delete nodata value
            cog_ar = cog.read(1)
            cog_ar = numpy.where(cog_ar==cog.nodata,numpy.nan,cog_ar)
    
            # stats
            driver = str(cog.meta['driver'])
            dtype = str(cog.meta['dtype'])
            crs = str(cog.meta['crs'])
            width = cog.meta['width']
            height = cog.meta['height']
            nodata = len(cog_ar[numpy.isnan(cog_ar)])
            data_with_values = len(cog_ar[~numpy.isnan(cog_ar)])
            pixel_size = cog.transform[0]
            
            cog_min = numpy.nanmin(cog_ar)
            cog_max = numpy.nanmax(cog_ar)
            cog_range = cog_max-cog_min
            cog_q1 = numpy.nanquantile(cog_ar, 0.25)
            cog_q3 = numpy.nanquantile(cog_ar, 0.75)
            cog_mean = numpy.nanmean(cog_ar)
            cog_median = numpy.nanmedian(cog_ar)
            cog_std = numpy.nanstd(cog_ar)
            cog_var = numpy.nanvar(cog_ar)
    
            cur_row = [cur_name,
                    resampling,
                    overview,
                    driver,
                    dtype,
                    crs,
                    width,
                    height,
                    nodata,
                    data_with_values,
                    pixel_size,
                    cog_min,
                    cog_max,
                    cog_range,
                    cog_q1,
                    cog_q3,
                    cog_mean,
                    cog_median,
                    cog_std,
                    cog_var]
            
            rows.append(cur_row)
            # name of csv file
            opath = path+'stats_{}.csv'
            output = opath.format(cur_name)
            
            # writing to csv file 
            with open(output, 'w',newline='') as csvfile: 
                csvwriter = csv.writer(csvfile) 
                csvwriter.writerow(fields) 
                csvwriter.writerow(cur_row)
                
    # name of csv file
    output = "{}/stats_all.csv".format(path)

    # writing to csv file 
    with open(output, 'w',newline='') as csvfile: 
        csvwriter = csv.writer(csvfile) 
        csvwriter.writerows(rows)
Beispiel #22
0
 def show_hist(self, bands=1, bins=50, **kwargs):
     show_hist(self.read(bands), bins=bins, **kwargs)
Beispiel #23
0
# Empty pixel https://mapbox.github.io/rasterio/topics/masks.html

# Calculate the stats for all channels

stats = []

# Read all bands at one go
bands = raster.read()

for band in bands:
    stats.append({
        'min': band.min(),
        'max': band.max(),
        'median': np.median(band),  #median on np(numpyssa), muut band
        'mean': band.mean()
    })
stats
# Visualize near infrared
show(nir, cmap='terrain')

# Visualize the histogram

from rasterio.plot import show_hist
show_hist(raster,
          bins=50,
          lw=0.0,
          stacked=False,
          alpha=0.3,
          histtype='stepfilled',
          title='Histogram')
import rasterio
from rasterio.plot import show_hist
import numpy as np

path = r"F:\WORDWIDE_Resample\Merge_predict_ssw\Merge\Union/"
from scipy import stats
with rasterio.open(path + 'Union201604.tif') as src:
    array = src.read(1)

    show_hist(array,
              bins=50,
              lw=0.0,
              stacked=False,
              alpha=0.3,
              histtype='stepfilled',
              title="Histogram")
    array = array.flatten()
    array = np.delete(array, np.where(array == 0), None)
    print(stats.normaltest(array))

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import pandas

from scipy.stats import norm

x = array
print(x)
mu = np.mean(x)  #计算均值
sigma = np.std(x)
Beispiel #25
0
                 "width": out_image.shape[2],
                 "transform": out_transform})
    
with rio.open("RGB_sopo_big_masked.tif", "w", **out_meta) as dest:
    dest.write(out_image)
    
rgb_plt = rio.open('RGB_sopo_big_masked.tif')
fig = plt.figure(figsize=(16,16))
plt.imshow(rgb_plt.read(1), cmap='pink')    

#subplot histogram and image !!!!!
from rasterio.plot import show_hist

fig, (axrgb, axhist) = plt.subplots(1, 2, figsize=(14,7))
show(rgb_plt, ax=axrgb)
show_hist(rgb_plt, bins=50, histtype='stepfilled',
     lw=0.0, stacked=False, alpha=0.3, ax=axhist)
plt.show()    


with rio.open(R10+'T18NXL_20200109T152631_B04.jp2') as src:
    out_image, out_transform = rio.mask.mask(src, sopo_proj.geometry,crop=True)
    out_meta = src.meta.copy()
    out_meta.update({"driver": "GTiff",
                 "height": out_image.shape[1],
                 "width": out_image.shape[2],
                 "transform": out_transform})
    
with rio.open("RGB_big_red.tif", "w", **out_meta) as dest:
    dest.write(out_image)
    
with rio.open(R10+'T18NXL_20200109T152631_B08.jp2') as src:
Beispiel #26
0
def main():
    print("start")
    print(datetime.now())
    ######   Test cases different dem tiles url and appropriate bbox in lon,lat EPSG:4326
    ##    # define the select window longitude and latitude
    ####    url="http://datacube-prod-data-public.s3.ca-central-1.amazonaws.com/store/dem/cdem/cdem-25-dem.tif"
    ####    miny=-64.7
    ####    maxy=-64.8
    ####    minx=46.5
    ####    maxx=46.6
    ####
    ####    # JF's original coordinates (was not completed after 15 minutes on country internet)
    ####    url="http://datacube-prod-data-public.s3.ca-central-1.amazonaws.com/store/dem/cdem/cdem-11-dem.tif"
    ####    miny=-63.5
    ####    maxy=-68.5
    ####    minx=63.25
    ####    maxx=68.25
    ####    # Norah had to use a smaller size (download took aprox 8 minutes on country internet)
    ####    miny=-68.5
    ####    maxy=-66.5
    ####    minx=66.25
    ####    maxx=68.25
    ##
    ##    #http://datacube-prod-data-public.s3.ca-central-1.amazonaws.com/store/dem/cdem/cdem-7-dem.tif
    ##    miny=-139.5
    ##    maxy=-137.5
    ##    minx=60.0
    ##    maxx=62.0
    ##    ## open cog by url
    ##
    ##    url="http://datacube-prod-data-public.s3.ca-central-1.amazonaws.com/store/dem/cdem/cdem-7-dem.tif"
    ##    file_name="./sample-%s"%(url.split('/')[-1])
    ##    # open witn all types of GeoTIFF georeference except that within the TIFF file’s keys and tags turned off
    ##
    ##    cog=rasterio.open(url,GEOREF_SOURCES='INTERNAL')
    ##    #cog bounds and crs
    ##    print(cog.bounds)
    ##    print(cog.crs)
    ##    print(cog.dtypes[0])
    ##    print(cog.transform)
    ##    print(cog.nodata)
    ##    print(cog.shape)
    ##    print(cog.meta)
    ##    print(cog.block_shapes)
    ##    #reproject the window in the cogs projection
    ##    llbox=box(miny,minx,maxy,maxx)
    ##    coords_window=shape(transform_geom('EPSG:4326',cog.crs,mapping(llbox)))
    ##    # select window bounds as var
    ##    wb=coords_window.bounds
    ##    print(wb)
    ##    # create the sample window from the bounds using the cogs (rasterio) window method
    ##    sample_window=cog.window(wb[0],wb[1],wb[2],wb[3])
    ##    print(sample_window)
    ##    # read the sample from the image,
    ##    # underlying gdal functionality may resample using nearest neighbour
    ##    # based on your download speed this could take a while
    ##    sample_cog=cog.read(1,window=sample_window)
    ##    print(sample_cog)
    ##    # write the sample out to a file 'sample_<filename>'
    ##    with rasterio.open(
    ##        file_name,
    ##        'w',
    ##        driver='GTiff',
    ##        height=sample_cog.shape[0],
    ##        width=sample_cog.shape[1],
    ##        count=1,
    ##        dtype=cog.dtypes[0],
    ##        crs=cog.crs,
    ##        transform=cog.transform,
    ##        nodata=cog.nodata,
    ##        GEOREF_SOURCES='INTERNAL'
    ##    ) as dst:
    ##        dst.write(sample_cog, 1)
    ##    dst.close()
    ##    cog.close()

    ###################### getting histogram statistics using rasterio, matplotlib and numpy
    import rasterio
    from rasterio.plot import show_hist, show
    from matplotlib import pyplot
    from mpl_toolkits.mplot3d import Axes3D
    import numpy
    # if using all code from above pass file name to sample, if not then define sample
    ##sample=file_name
    sample = 'C:\\users\\nbrown\\documents\\datacube\\stage\\example-code\\sample-cdem-7-dem.tif'
    cog_sample = rasterio.open(sample)
    print("bounds: %s" % (str(cog_sample.bounds)))
    print("crs: %s" % (cog_sample.crs))
    print("data type: %s" % (str(cog_sample.dtypes[0])))
    print("transform: %s" % str((cog_sample.transform)))
    print("pixel resolution from transform: %s" %
          (str(cog_sample.transform[0])))
    print("no data: %s" % (str(cog_sample.nodata)))
    print("image size in pixes: %s" % (str(cog_sample.shape)))
    print("cog header info: %s" % (cog_sample.meta))

    #make a figure with two axes subplot
    fig, (aximage, axhist) = pyplot.subplots(1, 2, figsize=(7, 4))
    figtitle = "original sample cog and histogram"
    fig.suptitle(figtitle, fontsize=10)

    #create histogram using rasterio show histogram, pass axes subplot handle to axhist
    bins = 50
    show_hist(cog_sample,
              bins=bins,
              lw=0.0,
              stacked=False,
              alpha=0.3,
              histtype='stepfilled',
              ax=axhist)
    axhist.set_title('')
    axhist.set_xlabel('elevation (m)')
    axhist.set_ylabel('')
    axhist.legend('')
    #create display image passing axes subplot handle to aximage
    show(cog_sample, cmap='gray', transform=cog_sample.transform, ax=aximage)
    #save the figure
    fname = './im-hist-test.png'
    pyplot.savefig(fname, format='png')
    #plot the figure
    ##    pyplot.show()

    #nmupy array gives lots of option
    cog_sample = rasterio.open(sample)
    #read cog into numpy array
    cog_ar = cog_sample.read(1)

    ##### 3D plots start
    # create a 3d axes
    fig = pyplot.figure(figsize=(7, 4))
    fig.suptitle("3d elevation (m)", fontsize=10)
    ax = fig.add_subplot(111, projection='3d')
    #create a 1D array for x /columns / longitude
    x = numpy.arange(cog_ar.shape[1])
    #create a 1D array for y/ rows / lattitude
    y = numpy.arange(cog_ar.shape[0])
    # merge two 1D arrays in a 2d xy array
    X, Y = numpy.meshgrid(x, y)
    # replace no data value with 'not a number'
    # could also try empty
    cog_ar = numpy.where(cog_ar == cog_sample.nodata, numpy.nan, cog_ar)
    cog_ar = numpy.where(cog_ar == cog_sample.nodata, numpy.nan, cog_ar)
    # wireframe handles nan without warning
    #ax.plot_wireframe(X,Y,cog_ar)
    ax.plot_surface(X, Y, cog_ar)

    # save plots to file
    pyplot.savefig('./test3d.png', format='png')
    #show plot
    pyplot.show()
    ####  3D plots end

    #get stats from array
    #min
    print(numpy.amin(cog_ar))
    #max
    print(numpy.amax(cog_ar))
    # plot the image
    #pyplot.show()
    #close image read
    cog_sample.close()
    print("finished")
    print(datetime.now())
Beispiel #27
0
def relatorio_metadados(banda):

    print('Buscando os metadados...')
    print('')
    print('')
    print(f'O nome do arquivo é: {banda.name}')
    print('')
    print(f'As dimensões são: {banda.width} x {banda.height} pixels;')
    print('')
    print(f'O tipo de dado é: {banda.dtypes}')
    print('')
    print(f'O sistema de referência de coordenadas é: {banda.crs}')
    print('')
    print(f'As coordenadas de canto são: {banda.bounds}')
    print('')
    print('')

    # Plotagem da imagem da banda

    print('Plotando a imagem...')
    print('')
    if banda == B_azul:
        plot.show(banda, cmap='Blues', title='Banda do azul')
    elif banda == B_verde:
        plot.show(banda, cmap='Greens', title='Banda do verde')
    elif banda == B_vermelho:
        plot.show(banda, cmap='Reds', title='Banda do vermelho')
    elif banda == B_NIR:
        plot.show(banda,
                  cmap='Oranges',
                  title='Banda do infravermelho próximo')
    else:
        pass
    print('Imagem plotada com sucesso!')
    print('')

    # Plotagem do histograma

    print('Plotando o histograma...')
    print('')
    if banda == B_azul:
        plot.show_hist(banda,
                       bins=100,
                       lw=0.0,
                       alpha=0.5,
                       title='Histograma - Banda do Azul')
    elif banda == B_verde:
        plot.show_hist(banda,
                       bins=100,
                       lw=0.0,
                       alpha=0.5,
                       title='Histograma - Banda do Verde')
    elif banda == B_vermelho:
        plot.show_hist(banda,
                       bins=100,
                       lw=0.0,
                       alpha=0.5,
                       title='Histograma - Banda do Vermelho')
    elif banda == B_NIR:
        plot.show_hist(banda,
                       bins=100,
                       lw=0.0,
                       alpha=0.5,
                       title='Histograma - Banda do Infravermelho Próximo')
    else:
        pass
    print('Histograma plotado com sucesso!')
    print('')

    return
Beispiel #28
0
from rasterio.plot import show, show_hist

from projections.atlas import atlas
from projections.rasterset import RasterSet, Raster
from projections.simpleexpr import SimpleExpr
import projections.predicts as predicts
import projections.rds as rds

# Import standard PREDICTS rasters
rasters = predicts.rasterset('rcp', 'aim', 2020, 'medium')
rs = RasterSet(rasters)
rs['logHPD_rs2'] = SimpleExpr('logHPD_rs', 'scale(log(hpd + 1), 0.0, 1.0)')

data1 = rs.eval('logHPD_rs')
data2 = rs.eval('logHPD_rs2')
data3 = np.where(np.isclose(data1, data2, equal_nan=True), 1, 0)
diff = np.fabs(data1 - data2)
print("max diff %f" % diff.max())

print("max in hpd_ref: %f" % rs['hpd_ref'].data.values.max())
print("max in hpd: %f" % rs['hpd'].data.dropna().values.max())

fig, ((ax1, ax2, ax3), (hx1, hx2, hx3)) = plt.subplots(2, 3, figsize=(21, 7))
show(data1, ax=ax1, cmap='Greens', title='Global max/min')
show(data2, ax=ax2, cmap='Greens', title='Computed max/min')
show(diff, ax=ax3, cmap='viridis', title='Difference', vmin=0, vmax=1.0)
show_hist(data1, ax=hx1, histtype='stepfilled')
show_hist(data2, ax=hx2, histtype='stepfilled')
show_hist(diff, ax=hx3, histtype='stepfilled')
plt.show()
Beispiel #29
0
show((raster, 1), cmap="Blues", ax=ax3)

# Set titles
ax1.set_title("Red")
ax2.set_title("Green")
ax3.set_title("Blue")

# Create true color composite

#Read channels into numpy arrays

red = raster.read(3)
green = raster.read(2)
blue = raster.read(1)

# Normalize the bands. This function was imported, so you don't need to write the code several times
# And if you have a mistake you need to correct it only once
redn = normalize(red)
greenn = normalize(green)
bluen = normalize(blue)

# Create the composite
rgb = np.stack((redn, greenn, bluen))
array

#Plot the RGB image (THIS doesn't work)
plt.imshow(rgb)

# Plot histogram of the data
show_hist(raster, bins=50, lw=0.0, stacked=False, alpha=0.3, histtype="stepfilled", title="Histogram of Landsat")
ply

#clip the raster with rasterio mask
for i in range(len(ply)):
	out_img, out_transform = mask(raster=rst[i], shapes=ply[i], crop=True)
	out_meta = rst[i].meta.copy()
	print(out_meta)

	#update metadata
	epsg_code = int(32618) #http://www.spatialreference.org/ref/epsg/wgs-84-utm-zone-18n/
	print(epsg_code)


	out_meta.update({"driver": "GTiff",
                 "height": out_img.shape[1],
                  "width": out_img.shape[2],
                  "transform": out_transform,
                  #"crs": pycrs.parser.from_epsg_code(epsg_code).to_proj4()}
                          })
    out_file = (out_path + out_name[i])
	with rasterio.open((out_file), "w", **out_meta) as dest:
		dest.write(out_img)
		dest.close()

#check the file by plotting map and histogram
for i in range(len(ply)):
	out_file = (out_path + out_name[i])
	clipped = rasterio.open(out_file)
	show((clipped), cmap='terrain')
	show_hist(clipped)
Beispiel #31
0
band_red = rasterio.open('LE07_L1TP_044034_20021222_20160927_01_T1_B3.tif')
band_nir = rasterio.open('LE07_L1TP_044034_20021222_20160927_01_T1_B4.tif')

red = band_red.read(1).astype('float64')
nir = band_nir.read(1).astype('float64')

ndvi = np.where((nir + red) == 0., 0, (nir - red) / (nir + red))

ndviImage = rasterio.open('NDVI_RASTERIO.jpg',
                          'w',
                          driver='Gtiff',
                          width=band_red.width,
                          height=band_red.height,
                          count=1,
                          crs=band_red.crs,
                          transform=band_red.transform,
                          dtype='float64')
ndviImage.write(ndvi, 1)
ndviImage.close()

ndvi = rasterio.open('NDVI_RASTERIO.jpg')
plot.show(ndvi, cmap='viridis', title='NDVI')
#plot.show(ndvi,cmap='RdYlGn',title='NDVI')
plot.show_hist(ndvi,
               bins=50,
               lw=0.0,
               stacked=False,
               alpha=0.3,
               histtype='stepfilled',
               title="Histogram")
Beispiel #32
0
plt.show()

from rasterio.plot import show
fig, (axdsm, axdtm, axchm) = plt.subplots(1, 3, figsize=(21, 7))
show(DSM, ax=axdsm, title='DSM')
show(DTM, ax=axdtm, title='DTM')
show(CHM, ax=axchm, title='CHM')
plt.show()
#plt.savefig('./outputimages/DSMDTMCHMImage.png')

from rasterio.plot import show_hist
fig, (axdsm, axdtm, axchm) = plt.subplots(1, 3, figsize=(21, 7))
show_hist(DSM,
          ax=axdsm,
          bins=100,
          lw=0.0,
          stacked=False,
          alpha=0.3,
          title="Histogram DSM")
show_hist(DTM,
          ax=axdtm,
          bins=100,
          lw=0.0,
          stacked=False,
          alpha=0.3,
          title="Histogram DTM")
show_hist(CHM,
          ax=axchm,
          bins=100,
          lw=0.0,
          stacked=False,
Beispiel #33
0
      red_normalised.mean())
print(green_normalised.min(), '-', green_normalised.max(), 'mean:',
      green_normalised.mean())
print(blue_normalised.min(), '-', blue_normalised.max(), 'mean:',
      blue_normalised.mean())

# Create RGB natural color composite
rgb = np.dstack((red_normalised, green_normalised, blue_normalised))

# Let's see how our color composite looks like
plt.imshow(rgb)

#Read and normalise NIR band
nir = raster.read(4)
nir_normalised = normalize(nir)

#Create the composite stacking
nrg = np.dstack((nir_normalised, red_normalised, green_normalised))

#Show the composite
plt.imshow(nrg)

#Show histogram
show_hist(raster,
          bins=50,
          lw=0.0,
          stacked=False,
          alpha=0.3,
          histtype='stepfilled',
          title="Histamiini")
Beispiel #34
0
out_img, out_transform = mask(raster=data, shapes=coords, crop=True)
# Copy the metadata
out_meta = data.meta.copy()

# Parse EPSG code
epsg_code = int(data.crs.data['init'][5:])

# Write the clipped raster to disk
out_meta.update({
    "driver": "GTiff",
    "height": out_img.shape[1],
    "width": out_img.shape[2],
    "transform": out_transform,
    "crs": pycrs.parser.from_epsg_code(epsg_code).to_proj4()
})

with rasterio.open(out_tif, "w", **out_meta) as dest:
    dest.write(out_img)

clipped = rasterio.open(out_tif)
show((clipped, 5))

# Show histogram for the clipped region
show_hist(clipped,
          bins=70,
          lw=0.0,
          stacked=False,
          alpha=0.3,
          histtype='stepfilled',
          title="Histogram")