I try to clip the blue band of the Sentinel 2 satellite image to a specific polygon in python and rasterio.
The clipping process seems to work fine, but when I write the clipped data to file
and then read it again all reflectance values are replaced.
import fiona
import rasterio
from rasterio.mask import mask
aoiFile = fiona.open('AOI.shp')
aoiGeom = [aoiFile[0]['geometry']]
rasterBand = rasterio.open('T33UUU_20180716T102019_B02_20m.jp2')
outImage, outTransform = mask(rasterBand, aoiGeom, crop=True)
outMeta = rasterBand.meta
outMeta.update({"driver": 'JP2OpenJPEG',
"height": outImage.shape[1],
"width": outImage.shape[2],
"transform": outTransform})
outRaster = rasterio.open('clipped_blue.jp2', "w", **outMeta)
outRaster.write(outImage)
outRaster.close()
print('clipped data from memory:')
print(outImage)
fileBlue = rasterio.open('clipped_blue.jp2').read(1)
print('')
print('clipped data from file:')
print(fileBlue)
Result:
clipped data from memory:
[[[ 0 0 0 0]
[ 0 0 938 992]
[ 0 970 980 909]
[ 0 859 941 0]
[ 0 742 936 0]
[ 0 867 927 0]
[ 0 833 914 0]
[ 0 864 911 0]
[ 0 867 894 0]
[ 0 860 867 0]
[ 0 738 786 0]]]
clipped data from file:
[[ 0 0 0 0]
[ 0 0 1024 1024]
[ 0 1024 1024 1024]
[ 0 1024 1024 0]
[ 0 1024 1024 0]
[ 0 1024 1024 0]
[ 0 1024 1024 0]
[ 0 1024 1024 0]
[ 0 1024 1024 0]
[ 0 1024 1024 0]
[ 0 1024 1024 0]]
Coordinates of shp file (content of variable aoiGeom, for replication purposes):
aoiGeom = [{'type': 'Polygon',
'coordinates': [[(359678.6200014538, 5820575.770123939),
(359686.5900014533, 5820691.660123938),
(359692.7600014533, 5820769.850123939),
(359734.89000145276, 5820768.14012394),
(359723.090001453, 5820641.480123938),
(359718.180001453, 5820566.930123939),
(359711.2000014535, 5820565.860123939),
(359682.0900014534, 5820568.83012394),
(359678.6200014538, 5820575.770123939)]]}]
question from:
https://stackoverflow.com/questions/65829060/python-rasterio-replaces-all-reflectance-values-with-1024-or-4096-of-clipped-sen 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…