Python Rasterio Writes JP2 without Colors

211 Views Asked by At

When opening a JP2 image in rasterio, the image seems to have the width and height dimensions flipped.

https://i.stack.imgur.com/rKxB0.png

So, I correct by changing the transform and Affine manually:

src = rasterio.open("img.JP2", 'r')
profile=src.profile
print("\nprofile",profile)
trnf = profile["transform"]
transform2 = rasterio.Affine(trnf[1], trnf[0], trnf[2], trnf[4], trnf[3], trnf[5])
profile["transform"] = transform2
print("\nprofile after",profile)

with rasterio.open("img_new.JP2", 'w', **profile.copy()) as src2:
    print(src.shape)
    print(src2.shape)
    print(src.read().shape)
    src2.write(src.read())   

Which outputs:

profile {'driver': 'JP2OpenJPEG', 'dtype': 'uint8', 'nodata': None, 'width': 23188, 'height': 19432, 'count': 4, 'crs': CRS.from_epsg(4326), 'transform': Affine(0.0, 4.629629629629355e-06, -112.05690972222226,
       -4.629629629629336e-06, 0.0, 33.10861342592594), 'blockxsize': 2048, 'blockysize': 2048, 'tiled': True, 'interleave': 'pixel'}

profile after {'driver': 'JP2OpenJPEG', 'dtype': 'uint8', 'nodata': None, 'width': 23188, 'height': 19432, 'count': 4, 'crs': CRS.from_epsg(4326), 'transform': Affine(4.629629629629355e-06, 0.0, -112.05690972222226,
       0.0, -4.629629629629336e-06, 33.10861342592594), 'blockxsize': 2048, 'blockysize': 2048, 'tiled': True, 'interleave': 'pixel'}
(19432, 23188)
(19432, 23188)
(4, 19432, 23188)

And saves the image with the corrected width and height, but without the colors:

with rasterio.open("img_new.JP2") as src2:
    show(src2)
    src2.close()

https://i.stack.imgur.com/AA6Ha.png

How can I write correctly so all colors are there?

I have tried grabbing different bands at once but it just does not seem to work when saving it.

0

There are 0 best solutions below