2

I'm using rasterio in Python at the moment, and I have no problem when I'm dealing with RGB satellite images. However, if I try using singleband Sentinel 2 images, or a singleband Sentinel 1 image, something happens. As this figure here shows, you can see that the image on the left, is suddenly green. Whilst the exact same image on the right in QGIS, looks at it should. Any suggestions?

enter image description here

I use the following code:

dataset = rasterio.open(project_dir + '/data/satellite_data/S1/merged/S1HH.tiff')
img=dataset.read()
fig=show(img)
2
  • I found out that if I import it to QGIS first, then saves the layer as a geotiff. It gets saved as an RGBA file (4 channels), which then shows up correctly and I essentially got what I wanted. Then in python I just flatten the image.
    – Kongie
    Commented Nov 12, 2018 at 17:18
  • Can you edit your question and add the import statements so we can see what libraries you are using.
    – user2856
    Commented Nov 12, 2018 at 20:11

1 Answer 1

8

This isn't rasterio reading the raster incorrectly. It's whatever you are using to display the data (matplotlib?) applying a default colour ramp. By saving as an RGBA in QGIS you are changing (and destroying) the data.

Instead, assuming you're using matplotlib, use the cmap argument in pyplot.imshow to specify a grayscale colourmap, something like:

from matplotlib import pyplot
import rasterio

dataset = rasterio.open(project_dir + '/data/satellite_data/S1/merged/S1HH.tiff')
img=dataset.read()
img_plt = pyplot.imshow(img, cmap='gray')
pyplot.show()

For a (very) basic contrast stretch:

import numpy as np

img[img == dataset.nodata] = np.nan  # Convert NoData to NaN
vmin, vmax = np.nanpercentile(img, (5,95))  # 5-95% stretch
img_plt = pyplot.imshow(img, cmap='gray', vmin=vmin, vmax=vmax)
pyplot.show()
4
  • Thank you Luke. Sounds plausible! (And important detail there!) I'll check it out tomorrow and get back to you.
    – Kongie
    Commented Nov 13, 2018 at 0:53
  • I couldn't wait, so snuck out of bed to check it out ;) That did the trick! Thank you @Luke. Do you per chance know of any way to brighten the picture up a bit. It looks extremely dark compared to the QGIS viewer.
    – Kongie
    Commented Nov 13, 2018 at 1:08
  • 1
    @Kongie. look up contrast stretching. This is what QGIS does. See edit.
    – user2856
    Commented Nov 13, 2018 at 3:39
  • perfect, think I found what I am looking for. Thank you =)
    – Kongie
    Commented Nov 13, 2018 at 14:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.