Пример #1
0
 def get_from_location(lon, lat):
     outlog(f"Finding parcel information for coordinates: {lon}, {lat}")
     parcel = parcel_info.by_location(aois.value, year.value, lon, lat,
                                      ptype.value, True, False, debug)
     pid = str(parcel['pid'][0])
     outlog(f"The parcel '{pid}' was found at this location.")
     try:
         get_data(parcel)
     except Exception as err:
         print(err)
Пример #2
0
def by_location(aoi, year, lon, lat, chipsize=512, extend=512,
                tms=['Google'], ptype=None, axis=True, debug=False):
    """Download the background image with parcels polygon overlay by selected
    location. This function will get an image from the center of the polygon.

    Examples:
        from cbm.view import background
        background.by_location(aoi, 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).
        debug, print or not procedure information (Boolean).
    """
    get_requests = data_source()
    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)))
        if debug:
            print('pid: ', pid)
            print('workdir: ', workdir)

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

    bg_path = normpath(join(workdir, 'backgrounds'))
    os.makedirs(bg_path, exist_ok=True)
    with open(f"{bg_path}/chipsize_extend_{chipsize}_{extend}", "w") as f:
        f.write('')

    if debug:
        print('bg_path: ', bg_path)
        print('lon, lat:', lon, lat)
    for t in tms:
        if debug:
            print('lon, lat, chipsize, extend, t, bg_path, debug')
            print(lon, lat, chipsize, extend, t, bg_path, debug)
        get_requests.background(lon, lat, chipsize, extend, t, bg_path, debug)
Пример #3
0
def by_location(aoi, year, lon, lat, tstype, ptype=None, band='', debug=False):
    """Download the time series for the selected year

    Examples:
        import cbm
        cbm.get.time_series.by_location(aoi, year, lon, lat, tstype)

    Arguments:
        aoi, the area of interest and year e.g.: es2019, nld2020 (str)
        lon, lat, the the coords of the parcel (float).
    """
    get_requests = data_source()
    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 = config.get_value(['paths', 'temp'])
    file_ts = normpath(
        join(workdir, aoi, year, str(pid), f'time_series_{tstype}{band}.csv'))
    if debug:
        print(file_ts)
        print(parcel)
    ts = json.loads(
        get_requests.parcel_ts(aoi, year, pid, tstype, ptype, band, debug))
    try:
        if isinstance(ts, pd.DataFrame):
            ts.to_csv(file_ts, index=True, header=True)
        elif isinstance(ts, dict):
            os.makedirs(os.path.dirname(file_ts), exist_ok=True)
            df = pd.DataFrame.from_dict(ts, orient='columns')
            df.to_csv(file_ts, index=True, header=True)
        if debug:
            print(f"File saved at: {file_ts}")
        return ts
    except Exception as err:
        return f"Could not create the file: {err}"

    return ts
Пример #4
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()