Пример #1
0
def plot_RGB(geotif, rgb_bands=[1,2,3], file_extension='jpg', dpi=150, figsize=(10,10)):
    """
    Calculates a RGB image (True color composite) based on red, greed, and blue bands.

    :param geotif: geotif file containning one band with NDVI values
    :param file_extension: format of the output graphic. default='png'
    :param rgb_bands: order of bands storing red, green and blue values default=[1,2,3]

    :result str: path to graphic file
    """
    from numpy import dstack

    gdal.UseExceptions()
    ds = gdal.Open(geotif)
    data = ds.ReadAsArray()
    gt = ds.GetGeoTransform()
    proj = ds.GetProjection()

    inproj = osr.SpatialReference()
    inproj.ImportFromWkt(proj)

    projcs = inproj.GetAuthorityCode('PROJCS')
    projection = ccrs.epsg(projcs)
    # print(projection)

    subplot_kw = dict(projection=projection)
    fig, ax = plt.subplots( subplot_kw=subplot_kw)

    extent = (gt[0], gt[0] + ds.RasterXSize * gt[1],
              gt[3] + ds.RasterYSize * gt[5], gt[3])

    red = ds.GetRasterBand(rgb_bands[0])
    green = ds.GetRasterBand(rgb_bands[1])
    blue = ds.GetRasterBand(rgb_bands[2])   # band 1 PSSCINE4Band blue

    img_r = red.ReadAsArray(0, 0, ds.RasterXSize, ds.RasterYSize)
    img_g = green.ReadAsArray(0, 0, ds.RasterXSize, ds.RasterYSize)
    img_b = blue.ReadAsArray(0, 0, ds.RasterXSize, ds.RasterYSize)

    # rgb = dstack((data[0, :, :], data[1, :, :], data[2, :, :]))

    rgb = dstack([img_r, img_g, img_b])
    img = ax.imshow(rgb, extent=extent, origin='upper', transform=projection)

    # img = ax.imshow(rgb.transpose((1, 2, 0)), extent=extent,
    #                 origin='upper')

    ax.gridlines(color='lightgrey', linestyle='-')
    # ax.set_xticks()

    tcc_plot = vs.fig2plot(fig, dpi=dpi, figsize=figsize, file_extension='jpg')

    plt.close()
    ds = None
    return tcc_plot
    def _handler(self, request, response):
        from tempfile import mkstemp

        tic = dt.now()
        init_process_logger('log.txt')
        response.outputs['output_log'].file = 'log.txt'

        LOGGER.info('Start process')
        response.update_status('Execution started at : {}'.format(tic), 1)

        ######################################
        # Read inputs
        ######################################
        try:
            resource = archiveextract(
                resource=rename_complexinputs(request.inputs['resource']))[0]
            fmts = [e.data for e in request.inputs['fmt']]
            title = request.inputs['title'][0].data

        except Exception as e:
            msg = 'Failed to read input parameter {}'.format(e)
            LOGGER.error(msg)
            raise Exception(msg)

        response.update_status('Input parameters ingested', 2)

        try:
            fig = map_spatial_analog(resource, title=title)
            output = []

            for fmt in fmts:
                output.append(fig2plot(fig, fmt))

        except Exception as e:
            msg = "Failed to create figure: {}".format(e)
            LOGGER.error(msg)
            raise Exception(msg)

        finally:
            plt.close()

        if len(fmts) == 1:
            output = output[0]
        else:
            output = archive(output)

        response.outputs['output_figure'].file = output
        response.update_status("done", 100)
        return response
Пример #3
0
def plot_products(products, extend=[10, 20, 5, 15]):
    """
    plot the products extends of the search result

    :param products: output of sentinel api search

    :return graphic: map of extents
    """

    import numpy as np

    from matplotlib.patches import Polygon
    import matplotlib.patches as mpatches
    from matplotlib.collections import PatchCollection

    from cartopy import config as cartopy_config
    import cartopy.feature as cfeature
    from cartopy.util import add_cyclic_point
    import re


    fig = plt.figure(dpi=90, facecolor='w', edgecolor='k')
    projection = ccrs.PlateCarree()
    ax = plt.axes(projection=projection)
    ax.set_extent(extend)
    ax.stock_img()
    ax.coastlines()
    ax.add_feature(cfeature.BORDERS)

    pat = re.compile(r'''(-*\d+\.\d+ -*\d+\.\d+);*''')

    for key in products.keys():
        polygon = str(products[key]['footprint'])

        # s = 'POLYGON ((15.71888453311329 9.045763865974665,15.7018748825589 8.97110837227606,15.66795226563288 8.822558900399137,15.639498612331632 8.69721920092792,15.63428409805786 8.674303514900869,15.600477269179995 8.525798537094156,15.566734239298787 8.377334323160321,15.53315342410745 8.228822837291709,15.499521168391912 8.080353481086165,15.493321895031096 8.052970059354971,14.999818486685434 8.053569047879877,14.999818016115439 9.046743365203026,15.71888453311329 9.045763865974665))'
        matches = pat.findall(polygon)
        if matches:
            xy = np.array([map(float, m.split()) for m in matches])
            ax.add_patch(mpatches.Polygon(xy, closed=True,  transform=ccrs.PlateCarree(), alpha=0.4)) # color='coral'
    # ccrs.Geodetic()

    ax.gridlines(draw_labels=True,)
    img = vs.fig2plot(fig, output_dir='.')

    return img
Пример #4
0
def plot_ndvi(geotif, file_extension='jpg', dpi=150, figsize=(10,10)):
    """
    plots a NDVI image

    :param geotif: geotif file containning one band with NDVI values
    :param file_extension: format of the output graphic. default='png'

    :result str: path to graphic file

    """
    #     https://ocefpaf.github.io/python4oceanographers/blog/2015/03/02/geotiff/

    gdal.UseExceptions()
    norm = vs.MidpointNormalize(midpoint=0)

    ds = gdal.Open(geotif)
    gt = ds.GetGeoTransform()
    proj = ds.GetProjection()
    inproj = osr.SpatialReference()
    inproj.ImportFromWkt(proj)
    projcs = inproj.GetAuthorityCode('PROJCS')
    projection = ccrs.epsg(projcs)
    # print("Projection: %s  " % projection)
    subplot_kw = dict(projection=projection)
    fig, ax = plt.subplots( subplot_kw=subplot_kw)

    extent = (gt[0], gt[0] + ds.RasterXSize * gt[1],
    gt[3] + ds.RasterYSize * gt[5], gt[3])


    bnd1 = ds.GetRasterBand(1)
    data = bnd1.ReadAsArray(0, 0, ds.RasterXSize, ds.RasterYSize) # buf_xsize=ds.RasterXSize/10, buf_ysize=ds.RasterYSize/10,

    img_ndvi = ax.imshow(data, extent=extent,origin='upper', norm=norm, vmin=-1, vmax=1, cmap=plt.cm.BrBG, transform=projection)
    # img_ndvi = ax.imshow(data, extent=extent,   # [:3, :, :].transpose((1, 2, 0))
    #                 origin='upper',norm=norm, vmin=-1, vmax=1, cmap=plt.cm.summer)

    plt.title('NDVI')
    plt.colorbar(img_ndvi)
    ax.gridlines() #draw_labels=True,

    ndvi_plot = vs.fig2plot(fig, output_dir='.', file_extension=file_extension, dpi=dpi, figsize=figsize)

    return ndvi_plot  # ndvi_plot
Пример #5
0
                             extent=extent,
                             origin='upper',
                             norm=norm,
                             vmin=-1,
                             vmax=1,
                             cmap=plt.cm.BrBG)
        # img_ndvi = ax.imshow(data, extent=extent, transform=projection,  # [:3, :, :].transpose((1, 2, 0))
        #                 origin='upper',norm=norm, vmin=-1, vmax=1, cmap=plt.cm.summer)

        plt.title('NDVI')
        plt.colorbar(img_ndvi)
        ax.gridlines()  #draw_labels=True,

from flyingpigeon import visualisation as vs

ndvi_plot = vs.fig2plot(fig, output_dir='.')

#
#
# from osgeo import gdal, osr
# from matplotlib import pyplot as plt
# from flyingpigeon import visualisation as vs
#
# gdal.UseExceptions()
#
# fname = '/home/nils/data/ndvi_SENTINE2ogmvEh.tif'
#
# ds = gdal.Open(fname)
# # data = ds.ReadAsArray()
# gt = ds.GetGeoTransform()
# proj = ds.GetProjection()
Пример #6
0
ax.add_patch(
    mpatches.Polygon(xy + 2,
                     closed=True,
                     transform=ccrs.PlateCarree(),
                     color='coral',
                     alpha=0.6))
# ccrs.Geodetic()
ax.gridlines(draw_labels=True, )

# plt.show()
#

# ax.add_patch(polygon)

from flyingpigeon import visualisation as vs
img = vs.fig2plot(fig, output_dir='/home/nils/data')

print img
plt.show()

# xy = np.array([[14.091911258909906, 8.141018593002007],
# [15.088597794983281, 8.142024478978072],
# [15.088393218629665, 7.14880742704817],
# [14.09400773070998, 7.147925563681057],
# [14.091911258909906, 8.141018593002007]])
#
#
# fig, ax = plt.subplots()
# patches = []
# num_polygons = 5
# num_sides = 5