Date   

Re: Silencing PROJ errors/warnings

Sean Gillies
 

Hi Greg,

On Fri, Mar 27, 2020 at 12:29 PM <gberardinelli@...> wrote:
Hi all,

As of GDAL 3 I've started seeing warnings written to stderr on open, such as:

proj_create_from_database: datum not found
It's possible that these datasets have malformed projection information, but in cases where I don't care I'd like to be able to silence these types of warnings, as they can easily be emitted hundreds of times.  However I can't find a way to do so.

Using an Env() context with CPL_DEBUG set to os.devnull has no effect, nor does redirecting sys.stderr itself.  It also doesn't look like this is being emitted through the logging module.  So it seems like the underlying library itself may be writing to stderr?  I don't know if this is a rasterio issue, a gdal issue, or a proj issue.

Any pointers are appreciated.

Greg

Do you see a bare "proj_create_from_database: datum not found" or do you see
ERROR 1: PROJ: proj_create_from_database: datum not found
as in https://github.com/OSGeo/gdal/issues/2321?

Which specific GDAL version are you using?

--
Sean Gillies


Silencing PROJ errors/warnings

gberardinelli@...
 

Hi all,

As of GDAL 3 I've started seeing warnings written to stderr on open, such as:

proj_create_from_database: datum not found
It's possible that these datasets have malformed projection information, but in cases where I don't care I'd like to be able to silence these types of warnings, as they can easily be emitted hundreds of times.  However I can't find a way to do so.

Using an Env() context with CPL_DEBUG set to os.devnull has no effect, nor does redirecting sys.stderr itself.  It also doesn't look like this is being emitted through the logging module.  So it seems like the underlying library itself may be writing to stderr?  I don't know if this is a rasterio issue, a gdal issue, or a proj issue.

Any pointers are appreciated.

Greg


Re: Applying Color Ramp to Single-Band Grayscale Images

Sean Gillies
 

Hi,

Have you seen https://rasterio.readthedocs.io/en/latest/topics/color.html#writing-colormaps ? It shows how to write a colormap (or color "ramp") to a new file. You can also open an existing file in "r+" mode and call the dataset's write_colormap() method.

On Tue, Mar 24, 2020 at 4:12 PM <nathan.raley@...> wrote:
Does anyone have any methods of applying a color ramp to a grayscale image? 

I have a NDVI calculated image I am trying to apply color ramp for the decimal based value ranges, but have no idea how to accomplish this.  I was wandering if this was possible via any of the rasterio libraries, and, if so, how would one go about accomplishing this?  I have other band based calculations I'd like to attempt, but until I can figure out how to apply the color ramps, I am at a stand still.

Thanks,

--
Sean Gillies


Re: [EXTERNAL] [rasterio] Applying Color Ramp to Single-Band Grayscale Images

nathan.raley@...
 

Actually, that second link looked like he had the format where it was using decimal based values, that might work.  I'll give it a try.  Thanks!


Re: [EXTERNAL] [rasterio] Applying Color Ramp to Single-Band Grayscale Images

nathan.raley@...
 

Thanks Trent,

I have looked into that, but the part of using the colormap.txt portion still is a bit confusing.  I haven't been able to find sufficient documentation on how to create that file to apply the color, or a ramp between two color ranges, for the values.  I did find a method in the python wrapper library for gdal that supported creating a color ramp for ranges using a specified color; however, that only supported whole number values and not the float based values you get from the NDVI image.


Re: [EXTERNAL] [rasterio] Applying Color Ramp to Single-Band Grayscale Images

Hare, Trent M
 

Nathan,
  Not sure about using rasterio, but have you tried gdaldem using "color-relief"?


shows creating a colorized image and adding hillshade (hillshade step not needed here):

-Trent


From: main@rasterio.groups.io <main@rasterio.groups.io> on behalf of nathan.raley via Groups.Io <nathan.raley@...>
Sent: Tuesday, March 24, 2020 3:12 PM
To: main@rasterio.groups.io <main@rasterio.groups.io>
Subject: [EXTERNAL] [rasterio] Applying Color Ramp to Single-Band Grayscale Images
 
Does anyone have any methods of applying a color ramp to a grayscale image? 

I have a NDVI calculated image I am trying to apply color ramp for the decimal based value ranges, but have no idea how to accomplish this.  I was wandering if this was possible via any of the rasterio libraries, and, if so, how would one go about accomplishing this?  I have other band based calculations I'd like to attempt, but until I can figure out how to apply the color ramps, I am at a stand still.

Thanks,


Applying Color Ramp to Single-Band Grayscale Images

nathan.raley@...
 

Does anyone have any methods of applying a color ramp to a grayscale image? 

I have a NDVI calculated image I am trying to apply color ramp for the decimal based value ranges, but have no idea how to accomplish this.  I was wandering if this was possible via any of the rasterio libraries, and, if so, how would one go about accomplishing this?  I have other band based calculations I'd like to attempt, but until I can figure out how to apply the color ramps, I am at a stand still.

Thanks,


Asyncio + Rasterio for slow network requests?

kylebarron2@...
 

I'm trying to improve performance of dynamic satellite imagery tiling, using
[`cogeo-mosaic-tiler`](https://github.com/developmentseed/cogeo-mosaic-tiler)/[`rio-tiler`](https://github.com/cogeotiff/rio-tiler),
which combines source Cloud-Optimized GeoTIFFs into a web mercator tile on the
fly. I'm using AWS Landsat and NAIP imagery stored in S3 buckets, and running
code on AWS Lambda in the same region.
 
Since NAIP imagery doesn't overlap cleanly with web mercator tiles, at zoom 12 I
have to load on average [6 assets to create one mercator
tile](https://user-images.githubusercontent.com/15164633/77286861-cfc7df00-6c99-11ea-84e9-8ed584b030c0.png).
While profiling the AWS Lambda instance using AWS X-Ray, I found that the
biggest bottleneck was the [base
call](https://github.com/cogeotiff/rio-tiler/blob/6b0d4df0b6aa1454c50312e8d352ed57f0a4e3cb/rio_tiler/utils.py#L449-L455)
to `WarpedVRT.read()`. That call always takes [between 1.7 and 2.0
seconds](https://user-images.githubusercontent.com/15164633/77289999-c5f5aa00-6ca0-11ea-816a-5aaf248a782c.png)
for each tile, regardless of the amount of overlap with the mercator tile.
 
When testing tile load times on an EC2 t2.nano in the same region, for the first
tile load, CPU time is 120 ms but wall time is 1.1 seconds. That leads me to
believe that the bottleneck is S3 latency.
 
If the code running on Lambda shares the same 90% proportion spent on latency
for each asset, that would imply that 9 seconds total are spent waiting on
latency.
 
Using multithreading with a `ThreadPoolExecutor` takes longer than running
single-threaded. Given the situation, it would seem ideal to use `asyncio` for
the COG network requests to improve performance.
 
Has this been attempted ever with Rasterio? I saw a [Rasterio example of using
async](https://github.com/mapbox/rasterio/blob/master/examples/async-rasterio.py)
to improve performance on a CPU bound function, and plan to try that out, but
I'm pessimistic about that approach directly because I'd think that the `async`
calls would need to be applied on the core fetch calls directly.
 
 
Reproduction for tile loading:
```py
import os
from rio_tiler.main import tile
os.environ['CURL_CA_BUNDLE'] = '/etc/ssl/certs/ca-certificates.crt'
os.environ['AWS_REQUEST_PAYER'] ="requester"
address = 's3://naip-visualization/ca/2018/60cm/rgb/34118/m_3411861_ne_11_060_20180723_20190208.tif'
x = 701
y = 1635
z = 12
tilesize = 512
%time data, mask = tile(address, x, y, z, tilesize)
```
```
CPU times: user 119 ms, sys: 20.3 ms, total: 140 ms
Wall time: 1.1 s
```


Re: Overwrite raster in place

Sean Gillies
 

It's not possible to change the shape of a raster dataset, the number of bands, or the data type in place.

On Wed, Mar 18, 2020 at 1:40 PM himat15 via Groups.Io <himat15=yahoo.com@groups.io> wrote:
I have two rasters, and one of them has one more column than the other. So I want to remove the last column in the larger one.
How can I change the raster width in place without having to do  a with open(f, 'r') and then another with open(f, 'w')?
I tried using r+, but when trying to do ds.width = 890, I got AttributeError: attribute 'width' of 'rasterio._base.DatasetBase' objects is not writable

with rio.open(f, 'r+') as ds:
        print(ds.profile) 
 
        ds_arr = ds.read(1) # Do I need to actually modify the np array here and then overwrite the file later?
        print(ds_arr.shape)
        
        profile = ds.profile
        
        width = profile['width']
        height = profile['height']
        
        if width == 891:
            ds.width = 890 # error
            
Profile: {'driver': 'GTiff', 'dtype': 'int16', 'nodata': -1.0, 'width': 891, 'height': 3081, 'count': 1, 'crs': CRS.from_epsg(32629), 'transform': Affine(15.0, 0.0, 232053.930561042,
       0.0, -15.0, 1438436.08069127), 'tiled': False, 'interleave': 'band'}



--
Sean Gillies


Overwrite raster in place

himat15@...
 

I have two rasters, and one of them has one more column than the other. So I want to remove the last column in the larger one.
How can I change the raster width in place without having to do  a with open(f, 'r') and then another with open(f, 'w')?
I tried using r+, but when trying to do ds.width = 890, I got AttributeError: attribute 'width' of 'rasterio._base.DatasetBase' objects is not writable

with rio.open(f, 'r+') as ds:
        print(ds.profile) 
 
        ds_arr = ds.read(1) # Do I need to actually modify the np array here and then overwrite the file later?
        print(ds_arr.shape)
        
        profile = ds.profile
        
        width = profile['width']
        height = profile['height']
        
        if width == 891:
            ds.width = 890 # error
            
Profile: {'driver': 'GTiff', 'dtype': 'int16', 'nodata': -1.0, 'width': 891, 'height': 3081, 'count': 1, 'crs': CRS.from_epsg(32629), 'transform': Affine(15.0, 0.0, 232053.930561042,
       0.0, -15.0, 1438436.08069127), 'tiled': False, 'interleave': 'band'}


Re: Rasterio Python Library Merging R, G, B Bands to Create a GeoReferenced GeoTiff

Sean Gillies
 

Hi,

On Wed, Mar 11, 2020 at 4:17 PM <nathan.raley@...> wrote:
I am attempting to use rasterio to merge 3 bands from Sentinel-2 data, sourced as .JP2 files, into a georeferenced GeoTiff.  However, I am running into 2 problems doing this.

First of all, here is my code for the merge:
    #Setup the bands
    b4 = rio.open(path + Bands.B04.value[0])
    b3 = rio.open(path + Bands.B03.value[0])
    b2 = rio.open(path + Bands.B02.value[0])
   
    #Setup the path for the constructed RGB image
    tif = path + "RGB.tif"
   
    #Create the RGB image
    with rio.open(tif, 'w', driver='Gtiff', width=b4.width, height=b4.height, count=3, crs=b4.crs, tranform=b4.transform, dtype=b4.dtypes[0], photometric="RGB", tile=True, compress='lzw', bigtiff=True) as rgb:
        rgb.write(b2.read(1), 1)
        rgb.write(b3.read(1), 2)
        rgb.write(b4.read(1), 3)
        rgb.close()
I have a couple comments on the code. You need to pass `tiled=True` to rasterio.open(), "tiled", and you should pass blockxsize and blockysize parameters as well. These must be multiples of 16. Also, you're passing "tranform" instead of "transform" and that will be ignored. This may explain why your output has no meaningful bounds.

I've found a pattern that makes dealing with a dataset's creation parameters a bit easier. In your case, it goes like this:

    rgb_profile = b4.profile
    rgb_profile.update(driver="GTiff", count=3, photometric="RGB", compress="LZW", bigtiff="IF_NEEDED", tiled=True, blockxsize=256, blockysize=256)
    with rasterio.open(tif, "w", **rgb_profile) as rgb:
        rgb.write(b2.read(1), 1)
        rgb.write(b3.read(1), 2)
        rgb.write(b4.read(1), 3)
 


Now, how do I copy the source projection information and bounds in the new GeoTiff I am creating?  Second, why is it showing up as all black when viewing the image in most common image browsers, but just fine in mapping software such as ArcMap or ArcGIS Pro?

Any ideas ?

I think it's likely that the common image browsers don't support some of the features of TIFF that GDAL uses. BIGTIFF is one of these.

--
Sean Gillies


Re: Decimated and windowed read in rasterio

umbertofilippo@...
 
Edited

Thanks to @Sean Gillies.

Posting here the solution I also posted on gis.stackexchange.com (https://gis.stackexchange.com/a/353869/9518).

Maybe it would be useful for others in search of a solution for a similar problem.

Basically, it is not possible to simultaneously make a windowed AND decimated read, so the answer to my question is NO.

However, there is an undocumented (AFAIK) parameter called overview_level which can be passed to rasterio.open().

This parameter takes the 0-based index of an overview level. So, assuming overviews are present in a source raster, one can do

src = rasterio.open(raster, overview_level=0)

to create a Rasterio dataset from the first level of overview of source raster.

Then, simply do a windowed read in the common format:

for ji, src_window in src.block_windows(1):
    arr = src.read(1, window=src_window)


Re: Decimated and windowed read in rasterio

umbertofilippo@...
 

The overview_level did the trick!

Thank you so much, I was after this for a long time.

Umberto Minora


Re: Decimated and windowed read in rasterio

umbertofilippo@...
 

On Thu, Mar 12, 2020 at 05:29 PM, Sean Gillies wrote:
Depending on the math, you may or may not get exactly the overview level you are looking for. If you absolutely need a particular overview level, I suggest passing an overview_level keyword argument to rasterio.open().
This is very interesting, I could not find the reference to overview_level in the documentation.
Definitely going to test it!
My aim is to read a specific overview (the greatest level) from a raster and resampling it by implementing a SUMMING algorithm.
Although this might sound like I am not supposed to use windows, this process is part of a more complex program where the user can also request the original resolution, and thus for very big dataset reading with windows is much better.
Will come back with my findings, meanwhile can you please point to a documentation if present where the open method is used alng with the overview_level paramenter?

Thank you so much,

Umberto Minora


Re: Any way to ensure cell resolutions stay square?

Luke
 

Try going the other way - multiply the resolution by a scale factor (i.e. 3 in your case) and divide the dimensions - see example gist

On Fri, 13 Mar 2020 at 14:35, himat15 via Groups.Io <himat15=yahoo.com@groups.io> wrote:
 
I am resampling a raster to become a different resolution, but it seems like the resolutions are not entirely accurate.

Here is the code I have (the code is very standard, taken from the documentation).

orig_res = ds.res[0] # Calculate scale factor for this specific input layer upscale_factor = orig_res / 15.0 print("upscale factor: ", upscale_factor) # Scale while reading in array scaled_arr = ds.read( out_shape=( ds.count, int(ds.height * upscale_factor), int(ds.width * upscale_factor) ), resampling=Resampling.bilinear ) # Also have to update the transform to be scaled scaled_transform = ds.transform * ds.transform.scale( (ds.height / scaled_arr.shape[1]), (ds.width / scaled_arr.shape[2]) ) scaled_profile = ds.profile scaled_profile.update(transform=scaled_transform, height=scaled_arr.shape[1], width=scaled_arr.shape[2]) with rio.open(f_out_path, 'w', **scaled_profile) as scaled_ds: scaled_ds.write(scaled_arr) print(f"Orig arr shape: ({ds.count}, {ds.shape[0]}, {ds.shape[1]})") print(f"Scaled ds shape: ({scaled_ds.count}, {scaled_ds.shape[0]}, {scaled_ds.shape[1]})") print("Orig ds res: ", ds.res) print("Scaled ds res: ", scaled_ds.res)

Code output:
upscale factor:  0.3333333333333333
Orig arr shape: (1, 9240, 2671)
Scaled ds shape: (1, 3080, 890)
Orig ds res:  (5.0, 5.0)
Scaled ds res:  (15.0, 15.00561797752809)

But in the final scaled ds resolution, why is the vertical scale direction slightly different? (15.0, 15.00561797752809)?

I'm not sure if it's a bad thing or not. I just want to make sure it's okay, or if there's a way to correct it, that would be good too.


Any way to ensure cell resolutions stay square?

himat15@...
 

 
I am resampling a raster to become a different resolution, but it seems like the resolutions are not entirely accurate.

Here is the code I have (the code is very standard, taken from the documentation).

orig_res = ds.res[0] # Calculate scale factor for this specific input layer upscale_factor = orig_res / 15.0 print("upscale factor: ", upscale_factor) # Scale while reading in array scaled_arr = ds.read( out_shape=( ds.count, int(ds.height * upscale_factor), int(ds.width * upscale_factor) ), resampling=Resampling.bilinear ) # Also have to update the transform to be scaled scaled_transform = ds.transform * ds.transform.scale( (ds.height / scaled_arr.shape[1]), (ds.width / scaled_arr.shape[2]) ) scaled_profile = ds.profile scaled_profile.update(transform=scaled_transform, height=scaled_arr.shape[1], width=scaled_arr.shape[2]) with rio.open(f_out_path, 'w', **scaled_profile) as scaled_ds: scaled_ds.write(scaled_arr) print(f"Orig arr shape: ({ds.count}, {ds.shape[0]}, {ds.shape[1]})") print(f"Scaled ds shape: ({scaled_ds.count}, {scaled_ds.shape[0]}, {scaled_ds.shape[1]})") print("Orig ds res: ", ds.res) print("Scaled ds res: ", scaled_ds.res)

Code output:
upscale factor:  0.3333333333333333
Orig arr shape: (1, 9240, 2671)
Scaled ds shape: (1, 3080, 890)
Orig ds res:  (5.0, 5.0)
Scaled ds res:  (15.0, 15.00561797752809)

But in the final scaled ds resolution, why is the vertical scale direction slightly different? (15.0, 15.00561797752809)?

I'm not sure if it's a bad thing or not. I just want to make sure it's okay, or if there's a way to correct it, that would be good too.


Re: Decimated and windowed read in rasterio

Sean Gillies
 

Hi,

On Thu, Mar 12, 2020 at 9:30 AM <umbertofilippo@...> wrote:

(Posted also on gis.stackexchange.com: https://gis.stackexchange.com/questions/353794/decimated-and-windowed-read-in-rasterio)

In my workflow using rasterio, I'd like to read an overview from a raster and get only a portion of it through a window at the same time.

Is this possible?

I have a pretty complex script so far and I'm trying to check whether the wrong output is due to this not being possible.

Basically, I am asking if it is possible to do something like this:

data = src.read(out_shape=(1,
                           math.ceil(src.height / 64),
                           math.ceil(src.width / 64)),
                window=window)

where data is a decimated read of src to get source raster overview for factor 64, and window has the width and height whose dimensions are relative to the source raster (not the overview).


the out_shape and window parameters of a Rasterio dataset's read method are very similar to the nBufXSize, nBufYSize, nXOff, nYOff, nXSize, and nYSize parameters of GDAL's RasterIO function. The window parameters refer to a region of the source raster at its full resolution, overviews are disregarded. The out_shape paramter determines the size of the output buffer and GDAL *may* read from overviews when they are available to reduce the cost of resampling.

Rasterio's read(), like GDAL's RasterIO, abstracts the details of full resolution vs overviews. Depending on the math, you may or may not get exactly the overview level you are looking for. If you absolutely need a particular overview level, I suggest passing an overview_level keyword argument to rasterio.open().

--
Sean Gillies


Decimated and windowed read in rasterio

umbertofilippo@...
 

(Posted also on gis.stackexchange.com: https://gis.stackexchange.com/questions/353794/decimated-and-windowed-read-in-rasterio)

In my workflow using rasterio, I'd like to read an overview from a raster and get only a portion of it through a window at the same time.

Is this possible?

I have a pretty complex script so far and I'm trying to check whether the wrong output is due to this not being possible.

Basically, I am asking if it is possible to do something like this:

data = src.read(out_shape=(1,
                           math.ceil(src.height / 64),
                           math.ceil(src.width / 64)),
                window=window)

where data is a decimated read of src to get source raster overview for factor 64, and window has the width and height whose dimensions are relative to the source raster (not the overview).


Rasterio Python Library Merging R, G, B Bands to Create a GeoReferenced GeoTiff

nathan.raley@...
 

I am attempting to use rasterio to merge 3 bands from Sentinel-2 data, sourced as .JP2 files, into a georeferenced GeoTiff.  However, I am running into 2 problems doing this.

First of all, here is my code for the merge:
    #Setup the bands
    b4 = rio.open(path + Bands.B04.value[0])
    b3 = rio.open(path + Bands.B03.value[0])
    b2 = rio.open(path + Bands.B02.value[0])
   
    #Setup the path for the constructed RGB image
    tif = path + "RGB.tif"
   
    #Create the RGB image
    with rio.open(tif, 'w', driver='Gtiff', width=b4.width, height=b4.height, count=3, crs=b4.crs, tranform=b4.transform, dtype=b4.dtypes[0], photometric="RGB", tile=True, compress='lzw', bigtiff=True) as rgb:
        rgb.write(b2.read(1), 1)
        rgb.write(b3.read(1), 2)
        rgb.write(b4.read(1), 3)
        rgb.close()

Now, how do I copy the source projection information and bounds in the new GeoTiff I am creating?  Second, why is it showing up as all black when viewing the image in most common image browsers, but just fine in mapping software such as ArcMap or ArcGIS Pro?

Any ideas?


Re: Transverse Mercator Complex projection

Luke
 

No. Exactly as I show in my code example. No need to write it out again, as you are just updating the georeferencing with the dataset opened in update mode ("r+").  The dataset is saved automatically when you exit the `with` statement context.

Luke