Beispiel #1
0
def maps(aoi, pid, chipsize=512, extend=512, tms='Google'):

    workdir = config.get_value(['paths', 'temp'])
    path = f'{workdir}/{aoi}/{pid}/backgrounds/'

    for t in tms:
        if not os.path.isfile(f'{path}{t.lower()}.png'):
            bg.by_pid(aoi, pid, chipsize, extend, t, True)

    columns = 5
    rows = int(len(tms) // columns + (len(tms) % columns > 0))
    fig = plt.figure(figsize=(25, 5 * rows))
    grid = ImageGrid(
        fig,
        111,  # similar to subplot(111)
        nrows_ncols=(rows, columns),  # creates grid of axes
        axes_pad=0.1,  # pad between axes in inch.
    )

    for ax, im in zip(grid, tms):
        # Iterating over the grid returns the Axes.
        ax.axis('off')
        ax.imshow(plt.imread(f'{path}{im.lower()}.png', 3))
        ax.set_title(im)

    plt.show()
Beispiel #2
0
def slider(aoi, pid, chipsize=512, extend=512, tms=['Google']):

    workdir = config.get_value(['paths', 'temp'])
    path = f'{workdir}/{aoi}/{pid}/'
    bg_path = f'{path}/backgrounds/'

    for t in tms:
        if not os.path.isfile(f'{bg_path}{t.lower()}.tif'):
            bg.by_pid(aoi, pid, chipsize, extend, t, True)

    with open(f'{path}info.json', "r") as f:
        json_data = json.load(f)

    def overlay_parcel(img, geom):
        patche = [
            PolygonPatch(feature,
                         edgecolor="yellow",
                         facecolor="none",
                         linewidth=2) for feature in geom['geom']
        ]
        return patche

    with rasterio.open(f'{bg_path}{tms[0].lower()}.tif') as img:
        img_epsg = img.crs.to_epsg()
        geom = spatial_utils.transform_geometry(json_data, img_epsg)
        patches = overlay_parcel(img, geom)

    selection = SelectionSlider(options=tms,
                                value=tms[0],
                                disabled=False,
                                continuous_update=False,
                                orientation='horizontal',
                                readout=True)
    output = Output()

    fig, ax = plt.subplots(figsize=(10, 10))
    with output:
        with rasterio.open(f'{bg_path}{selection.value.lower()}.tif') as img:
            for patch in patches:
                ax.add_patch(copy(patch))
            show(img, ax=ax)
        plt.show()

    def on_value_change(change):
        with output:
            output.clear_output()
            fig, ax = plt.subplots(figsize=(10, 10))
            with rasterio.open(
                    f'{bg_path}{selection.value.lower()}.tif') as im:
                for patch in patches:
                    ax.add_patch(copy(patch))
                show(im, ax=ax)
            plt.show()

    selection.observe(on_value_change, names='value')
    return VBox([selection, output])
Beispiel #3
0
def by_location(aoi,
                year,
                lon,
                lat,
                chipsize=512,
                extend=512,
                tms=['google'],
                ptype=None,
                columns=4,
                debug=False):
    """Show the background image with parcels polygon overlay by selected
    parcel id. This function will get an image from the center of the polygon.

    Examples:
        from cbm.view import background
        background.by_location(aoi, year, lon, lat, 512, 512, 'Google',
                                True, True)

    Arguments:
        aoi, the area of interest (str)
        year, the year of parcels table
        lon, lat, longitude and latitude in decimal degrees (float).
        chipsize, size of the chip in pixels (int).
        extend, size of the chip in meters  (float).
        tms, tile map server Google or Bing (str).
        columns, the number of columns of the grid
        debug, print or not procedure information (Boolean).
    """
    if type(tms) is str:
        tms = [tms]

    try:
        parcel = parcel_info.by_location(aoi, year, lon, lat, ptype, True,
                                         False, debug)
        if type(parcel['pid']) is list:
            pid = parcel['pid'][0]
        else:
            pid = parcel['pid']

        workdir = normpath(
            join(config.get_value(['paths', 'temp']), aoi, str(year),
                 str(pid)))
        parcel_id = True
    except Exception as err:
        workdir = normpath(
            join(config.get_value(['paths', 'temp']), aoi, str(year),
                 f'_{lon}_{lat}'.replace('.', '_')))
        parcel_id = False
        if debug:
            print("No parcel information found.", err)

    if len(tms) < columns:
        columns = len(tms)

    bg_path = normpath(join(workdir, 'backgrounds'))

    same_args = check_args(bg_path, chipsize, extend, debug)

    if debug:
        print('path: ', bg_path)
        print('same args: ', same_args)
        print('aoi-year-lon-lat-chipsize-extend-tms-ptype-columns-debug')
        print(aoi, year, lon, lat, chipsize, extend, tms, ptype, columns,
              debug)

    for t in tms:
        if not isfile(normpath(join(bg_path,
                                    f'{t.lower()}.tif'))) or not same_args:
            if parcel_id:
                get_bg.by_pid(aoi, year, pid, chipsize, extend, t, ptype, True,
                              debug)
            else:
                get_bg.by_location(aoi, year, lon, lat, chipsize, extend, t,
                                   ptype, True, debug)

    if parcel_id:
        with open(normpath(join(workdir, 'info.json')), 'r') as f:
            parcel = json.load(f)

        with rasterio.open(normpath(join(bg_path,
                                         f'{tms[0].lower()}.tif'))) as img:
            img_epsg = img.crs.to_epsg()
            geom = spatial_utils.transform_geometry(parcel, img_epsg)
            patches = overlay_parcel(img, geom)

    rows = int(len(tms) // columns + (len(tms) % columns > 0))
    fig = plt.figure(figsize=(30, 10 * rows))
    grid = ImageGrid(
        fig,
        111,  # similar to subplot(111)
        nrows_ncols=(rows, columns),  # creates grid of axes
        axes_pad=0.4,  # pad between axes in inch.
    )

    def overlay_title(img, date):
        date_text = ax.text(
            img.bounds.left + ((img.bounds.right - img.bounds.left) / 9),
            img.bounds.bottom + ((img.bounds.top - img.bounds.bottom) / 1.15),
            date,
            color='yellow',
            weight='bold',
            size=32 - columns * 2,
            bbox=dict(boxstyle="round", ec='yellow', fc='black', alpha=0.2))
        return date_text

    for ax, t in zip(grid, tms):
        with rasterio.open(normpath(join(bg_path, f'{t.lower()}.tif'))) as img:
            if parcel_id:
                for patch in patches:
                    ax.add_patch(copy(patch))
            overlay_title(img, t)
            show(img, ax=ax)


#            ax.xaxis.set_major_locator(ticker.MultipleLocator(200))

    if len(tms) > columns and columns * rows > len(tms):
        for ax in grid[-((columns * rows - len(tms))):]:
            ax.remove()

    plt.show()
Beispiel #4
0
def by_pid(aoi,
           year,
           pid,
           chipsize=512,
           extend=512,
           tms=['Google'],
           ptype=None,
           columns=4,
           debug=False):
    """Show the background image with parcels polygon overlay by selected
    parcel id. This function will get an image from the center of the polygon.

    Examples:
        from cbm.view import background
        background.by_location(aoi, year, lon, lat, 512, 512, 'Google',
                                True, True)

    Arguments:
        aoi, the area of interest (str)
        year, the year of parcels table
        pid, the parcel id (str).
        chipsize, size of the chip in pixels (int).
        extend, size of the chip in meters  (float).
        tms, tile map server Google or Bing (str).
        columns, the number of columns of the grid
        debug, print or not procedure information (Boolean).
    """

    if type(tms) is str:
        tms = [tms]
    if len(tms) < columns:
        columns = len(tms)

    workdir = normpath(
        join(config.get_value(['paths', 'temp']), aoi, str(year), str(pid)))
    bg_path = normpath(join(workdir, 'backgrounds'))

    same_args = check_args(bg_path, chipsize, extend)

    if debug:
        print('path: ', bg_path)
        print('same args: ', same_args)
        print('aoi, year, pid, chipsize, extend, tms, columns, debug')
        print(aoi, year, pid, chipsize, extend, tms, columns, debug)

    for t in tms:
        if not isfile(normpath(join(
                bg_path, f'{t.lower()}.tif'))) or same_args is False:
            get_bg.by_pid(aoi, year, pid, chipsize, extend, t, ptype, True,
                          debug)

    with open(normpath(join(workdir, 'info.json')), 'r') as f:
        parcel = json.load(f)

    with rasterio.open(normpath(join(bg_path,
                                     f'{tms[0].lower()}.tif'))) as img:
        img_epsg = img.crs.to_epsg()
        geom = spatial_utils.transform_geometry(parcel, img_epsg)
        patches = overlay_parcel(img, geom)

    rows = int(len(tms) // columns + (len(tms) % columns > 0))
    fig = plt.figure(figsize=(30, 10 * rows))
    grid = ImageGrid(
        fig,
        111,  # similar to subplot(111)
        nrows_ncols=(rows, columns),  # creates grid of axes
        axes_pad=0.4)  # pad between axes in inch.

    for ax, t in zip(grid, tms):
        with rasterio.open(normpath(join(bg_path, f'{t.lower()}.tif'))) as img:
            for patch in patches:
                ax.add_patch(copy(patch))


#             ax.xaxis.set_major_locator(ticker.MultipleLocator(200))
            show(img, ax=ax)
            ax.set_title(t, fontsize=20)

    if len(tms) > columns and columns * rows > len(tms):
        for ax in grid[-((columns * rows - len(tms))):]:
            ax.remove()

    plt.show()
Beispiel #5
0
def by_pid(aoi, year, pid, ptype=None, tms='osm', debug=False):
    """Show parcel information with an image with polygon overlay by selected
    parcel id. This function will get an image from the center of the polygon.

    Examples:
        from cbm.show import parcel_info
        parcel_info.by_id(aoi, year, pid)

    Arguments:
        aoi, the area of interest (str)
        year, the year of parcels table
        pid, the parcel id (str).
        ptype, parcel type
        debug, print or not procedure information (Boolean).
    """

    workdir = normpath(
        join(config.get_value(['paths', 'temp']), aoi, str(year), str(pid)))
    bg_path = normpath(join(workdir, 'backgrounds'))

    if debug:
        print('path: ', bg_path)
        print('aoi, year, pid, debug')
        print(aoi, year, pid, debug)

    file_info = normpath(join(workdir, 'info.json'))
    if not isfile(file_info):
        parcel_info.by_pid(aoi, str(year), str(pid), ptype, True)
    with open(normpath(join(workdir, 'info.json')), 'r') as f:
        parcel = json.load(f)

    plt.rcParams['font.size'] = 14
    plt.figure(figsize=(10, 3))
    gs = gridspec.GridSpec(1, 2)
    ax1 = plt.subplot(gs[0, 0])
    ax2 = plt.subplot(gs[0, 1])

    try:
        if not isfile(normpath(join(bg_path, f'{tms}.tif'))):
            get_bg.by_pid(aoi, year, pid, 256, 1024, tms, ptype, True, debug)
        elif getsize(normpath(join(bg_path, f'osm.tif'))) < 1000:
            get_bg.by_pid(aoi, year, pid, 256, 1024, tms, ptype, True, debug)
        with rasterio.open(normpath(join(bg_path, f'{tms}.tif'))) as img:
            img_epsg = img.crs.to_epsg()
            geom = spatial_utils.transform_geometry(parcel, img_epsg)
            patches = overlay_parcel(geom)
            for patch in patches:
                ax2.add_patch(copy(patch))
            show(img, ax=ax2)
    except Exception as err:
        print("Could not get image. ", err)

    text = [
        f"AOI: {aoi}", f"Year: {year}", f"Parcel ID: {pid}",
        f"Crop type: {parcel['cropname'][0]}",
        f"Crop type code: {parcel['cropcode'][0]}",
        f"Area: {parcel['area'][0]} sqm",
        f"Centroid (Lat/Lon): {parcel['clat'][0]:.6f}, {parcel['clon'][0]:.6f}",
        f"Geometry SRID: {parcel['srid'][0]}"
    ]
    first_line = 0.9
    for t in text:
        ax1.text(0, first_line, t)
        first_line -= 0.12

    ax1.axis('off')
    ax2.axis('off')
    plt.show()