Re: Applying Color Ramp to Single-Band Grayscale Images


Brandon Victor
 

Hello Eyat,

I just realised I didn't respond. Definitely, if it's not a once-off, a programmatic solution is the best way. Option #2 can be used with negative integers; the gotchya is that matplotlib interprets floating point numbers as scaling between 0-1, and integers as scaling between 0-256. You'll also have to set the dtype to int16 if your DEMs are stored in uint8 or int16 and you are doing a subtraction. You just have to set your range to include the negative values. Something like this (you can also replace np.int16 with np.float32 if you need):

```python
data = np.random.uniform(-256, 256, (100, 100)).astype(np.int16)
cmap_dict = {n: np.array(cmap(int((n+256)/2)))*256 for n in range(-256, 256, 2)}
with rasterio.open('scraps/mapped.tif', 'w', width=100, height=100, count=1, dtype=np.int16) as dst:
    dst.write(data, 1)
    dst.write_colormap(1, cmap_dict)
```

There are at least two reasons option #3 is not recommended:
  1. You bake the colours into the image, meaning that for downstream users, there's no practical way to recover the variable of interest from the image. That might be you, or it might be other people.
  2. You are multiplying your data storage requirements. This may or may not be relevant to you. Smaller files are easier to deal with.
Of course, the benefits of option #3 are that you have a more portable file; it could even be opened by a non-GIS image viewer. I assumed that processing utility was paramount; perhaps I shouldn't have.

Perhaps it's too untimely a response for you, but maybe it will help anyone else who stumbles on this page.

Join main@rasterio.groups.io to automatically receive all group messages.