Python rasterio.uint8() Examples

The following are 10 code examples of rasterio.uint8(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module rasterio , or try the search function .
Example #1
Source File: conftest.py    From earthpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def basic_image_tif(tmpdir, basic_image):
    """
    A GeoTIFF representation of the basic_image array.
    Borrowed from rasterio/tests/conftest.py

    Returns
    -------
    string path to raster file
    """
    outfilename = str(tmpdir.join("basic_image.tif"))
    kwargs = {
        "crs": rio.crs.CRS({"init": "epsg:4326"}),
        "transform": Affine.identity(),
        "count": 1,
        "dtype": rio.uint8,
        "driver": "GTiff",
        "width": basic_image.shape[1],
        "height": basic_image.shape[0],
        "nodata": None,
    }
    with rio.open(outfilename, "w", **kwargs) as out:
        out.write(basic_image, indexes=1)
    return outfilename 
Example #2
Source File: conftest.py    From earthpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def basic_image_tif_2(tmpdir, basic_image_2):
    """
    A GeoTIFF representation of the basic_image_2 array.
    Borrowed from rasterio/tests/conftest.py

    Returns
    -------
    string path to raster file
    """
    outfilename = str(tmpdir.join("basic_image_2.tif"))
    kwargs = {
        "crs": rio.crs.CRS({"init": "epsg:4326"}),
        "transform": Affine.identity(),
        "count": 1,
        "dtype": rio.uint8,
        "driver": "GTiff",
        "width": basic_image_2.shape[1],
        "height": basic_image_2.shape[0],
        "nodata": None,
    }
    with rio.open(outfilename, "w", **kwargs) as out:
        out.write(basic_image_2, indexes=1)
    return outfilename 
Example #3
Source File: conftest.py    From earthpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def basic_image_tif_CRS(tmpdir, basic_image):
    """
    A GeoTIFF representation of the basic_image array with a different CRS.
    Borrowed from rasterio/tests/conftest.py

    Returns
    -------
    string path to raster file
    """
    outfilename = str(tmpdir.join("basic_image_CRS.tif"))
    kwargs = {
        "crs": rio.crs.CRS({"init": "epsg:3857"}),
        "transform": Affine.identity(),
        "count": 1,
        "dtype": rio.uint8,
        "driver": "GTiff",
        "width": basic_image.shape[1],
        "height": basic_image.shape[0],
        "nodata": None,
    }
    with rio.open(outfilename, "w", **kwargs) as out:
        out.write(basic_image, indexes=1)
    return outfilename 
Example #4
Source File: io_util.py    From WaterNet with MIT License 5 votes vote down vote up
def save_bitmap(file_path, image, source):
    """Save a bitmap given as a 2D matrix as a GeoTIFF."""

    print("Save result at {}.".format(file_path))
    with rasterio.open(
            file_path,
            'w',
            driver='GTiff',
            dtype=rasterio.uint8,
            count=1,
            width=source.width,
            height=source.height,
            transform=source.transform) as dst:
        dst.write(image, indexes=1) 
Example #5
Source File: conftest.py    From earthpy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def basic_image():
    """
    A 10x10 array with a square (3x3) feature
    Equivalent to results of rasterizing basic_geometry with all_touched=True.
    Borrowed from rasterio/tests/conftest.py

    Returns
    -------
    numpy ndarray
    """
    image = np.zeros((10, 10), dtype=np.uint8)
    image[2:5, 2:5] = 1
    return image 
Example #6
Source File: conftest.py    From earthpy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def basic_image_2():
    """
    A 10x10 array with a square (3x3) feature
    Equivalent to results of rasterizing basic_geometry with all_touched=True.
    Borrowed from rasterio/tests/conftest.py

    Returns
    -------
    numpy ndarray
    """
    image = np.zeros((20, 20), dtype=np.uint8)
    image[2:5, 2:5] = 1
    return image 
Example #7
Source File: utils.py    From label-maker with MIT License 5 votes vote down vote up
def download_tile_tms(tile, imagery, folder, kwargs):
    """Download a satellite image tile from a tms endpoint"""

    image_format = get_image_format(imagery, kwargs)

    if os.environ.get('ACCESS_TOKEN'):
        token = os.environ.get('ACCESS_TOKEN')
        imagery = imagery.format_map(SafeDict(ACCESS_TOKEN=token))

    r = requests.get(url(tile.split('-'), imagery),
                     auth=kwargs.get('http_auth'))
    tile_img = op.join(folder, '{}{}'.format(tile, image_format))
    tile = tile.split('-')

    over_zoom = kwargs.get('over_zoom')
    if over_zoom:
        new_zoom = over_zoom + kwargs.get('zoom')
        # get children
        child_tiles = children(int(tile[0]), int(tile[1]), int(tile[2]), zoom=new_zoom)
        child_tiles.sort()

        new_dim = 256 * (2 * over_zoom)

        w_lst = []
        for i in range (2 * over_zoom):
            for j in range(2 * over_zoom):
                window = Window(i * 256, j * 256, 256, 256)
                w_lst.append(window)

        # request children
        with rasterio.open(tile_img, 'w', driver='jpeg', height=new_dim,
                        width=new_dim, count=3, dtype=rasterio.uint8) as w:
                for num, t in enumerate(child_tiles):
                    t = [str(t[0]), str(t[1]), str(t[2])]
                    r = requests.get(url(t, imagery),
                                    auth=kwargs.get('http_auth'))
                    img = np.array(Image.open(io.BytesIO(r.content)), dtype=np.uint8)
                    try:
                        img = img.reshape((256, 256, 3)) # 4 channels returned from some endpoints, but not all
                    except ValueError:
                        img = img.reshape((256, 256, 4))
                    img = img[:, :, :3]
                    img = np.rollaxis(img, 2, 0)
                    w.write(img, window=w_lst[num])
    else:
        r = requests.get(url(tile, imagery),
                         auth=kwargs.get('http_auth'))
        with open(tile_img, 'wb')as w:
            w.write(r.content)
    return tile_img 
Example #8
Source File: rastertoolz.py    From spandex with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def to_geotiff(array, src, path_to_tif):
        kwargs = src.meta
        kwargs.update(
            dtype=rasterio.uint8,
            count=1,
            compress='lzw')

        with rasterio.open(path_to_tif, 'w', **kwargs) as dst:
            dst.write_band(1, array.astype(rasterio.uint8))


# Modified version of rasterstats function of same name.  Added functionality to
# return the np array image of each geometry and apply arbitrary function instead
# of precanned set.  See notebook in the spandex examples dir for example usage. 
Example #9
Source File: statistics_rasterInpolygon.py    From python-urbanPlanning with MIT License 5 votes vote down vote up
def reprojectedRaster(rasterFn,ref_vectorFn,dst_raster_projected):
    dst_crs=gpd.read_file(ref_vectorFn).crs
    print(dst_crs) #{'init': 'epsg:4326'}    
    a_T = datetime.datetime.now()
    
    # dst_crs='EPSG:4326'
    with rasterio.open(rasterFn) as src:
        transform, width, height = calculate_default_transform(src.crs, dst_crs, src.width, src.height, *src.bounds)
        kwargs = src.meta.copy()
        kwargs.update({
        'crs': dst_crs,
        'transform': transform,
        'width': width,
        'height': height,
        # 'compress': "LZW",
        'dtype':rasterio.uint8,  #rasterio.float32
        })
        # print(src.count)

        with rasterio.open(dst_raster_projected, 'w', **kwargs) as dst:
            for i in range(1, src.count + 1):
                reproject(
                    source=rasterio.band(src, i),
                    destination=rasterio.band(dst, i),
                    src_transform=src.transform,
                    src_crs=src.crs,
                    dst_transform=transform,
                    dst_crs=dst_crs,
                    resampling=Resampling.nearest
                    )     
    
    b_T = datetime.datetime.now()
    print("reprojected time span:", b_T-a_T)    
 
#根据Polgyon统计raster栅格信息 
Example #10
Source File: sentinel2_processing.py    From NGVEO with MIT License 4 votes vote down vote up
def cloud_detection(self, input_file):
        print("cloud_detection", input_file)
        input_dir = os.path.join(input_file, "GRANULE")
        sub_directories = utils.get_immediate_subdirectories(input_dir)
        image_dir = os.path.join(input_dir, sub_directories[0], "IMG_DATA")

        input_bands = ['B01', 'B02', 'B04', 'B05', 'B08', 'B8A', 'B09', 'B10', 'B11', 'B12']  # Band order is strict
        # num_bands = len(input_bands)
        scale_factor = 10000.0 #Read from metadata ?
        band_paths = self.get_band_paths(input_file, input_bands)
        for band_ind, img_filename in enumerate(band_paths):
            with rasterio.open(img_filename) as ds:
                img = ds.read()
                if band_ind == 0:  # First band need to be 60m
                    tmparr = np.empty_like(img)
                    aff60 = ds.transform
                    img_stack = np.zeros((img.shape[0], img.shape[1], img.shape[2], len(input_bands)))
                    img_stack[:, :, :, band_ind] = img / scale_factor
                elif input_bands[band_ind].upper() == "B09" or input_bands[band_ind].upper() == "B10":  # 60m
                    img_stack[:, :, :, band_ind] = img / scale_factor
                else:
                    reproject(img, tmparr,
                              src_transform=ds.transform,
                              dst_transform=aff60,
                              src_crs=ds.crs,
                              dst_crs=ds.crs,
                              resampling=Resampling.bilinear)
                    img_stack[:, :, :, band_ind] = tmparr / scale_factor

                if input_bands[band_ind].upper() == "B02":  # 10m
                    aff10 = ds.transform
                    nrows10 = img.shape[1]
                    ncols10 = img.shape[2]
                    ds10 = ds

        cloud_detector = S2PixelCloudDetector(threshold=0.4, average_over=4, dilation_size=2)
        cloud_probs = cloud_detector.get_cloud_probability_maps(img_stack)
        cloud_mask = cloud_detector.get_cloud_masks(img_stack).astype(rasterio.uint8)

        cloud_probs_10 = np.zeros((1, nrows10, ncols10))
        reproject(cloud_probs, cloud_probs_10,
                  src_transform=aff60,
                  dst_transform=aff10,
                  src_crs=ds.crs,
                  dst_crs=ds.crs,
                  resampling=Resampling.cubic_spline)

        cloud_mask_10 = np.zeros((1, nrows10, ncols10))
        reproject(cloud_mask, cloud_mask_10,
                  src_transform=aff60,
                  dst_transform=aff10,
                  src_crs=ds.crs,
                  dst_crs=ds.crs,
                  resampling=Resampling.nearest)


        return (cloud_probs_10, cloud_mask_10, ds10)