0

I'm using rasterio to analyze satellite imagery stored in JPEG2000 format and am having the problem that pixel values change when opening and then saving the same file again. Any ideas why this happens?

with rasterio.open('/tmp/in.jp2') as infile:
    with rasterio.open('/tmp/out.jp2', 'w', count=infile.count, dtype=infile.dtypes[0], height=infile.height, width=infile.width, crs=infile.crs, transform=infile.transform) as outfile:
        outfile.write(infile.read())

    with rasterio.open('/tmp/in.jp2') as f:
        data = f.read()
        print(data.min(), data.max())
        # output: 0 19614

    with rasterio.open('/tmp/out.jp2') as f:
        data = f.read()
        print(data.min(), data.max())
        # output: 0 19596
6
  • Are you comparing pixel values with rasterio and qgis?
    – Helios
    Commented Mar 9, 2022 at 16:48
  • Both. In the above example, I use rasterio to compare the pixel ranges (note the difference). In QGIS, I can see a difference in the range of the "before" and "after" images, too. However, the absolute values are different from those reported by rasterio for some reason. Commented Mar 9, 2022 at 16:50
  • can you share the image with the values in rasterio and qgis?
    – Helios
    Commented Mar 9, 2022 at 16:58
  • 3
    Lossy compression will change the pixel values. See this note
    – mikewatt
    Commented Mar 9, 2022 at 18:40
  • 3
    JPEG2000 can be lossless but you did not show that you use appropriate parameters to make sure it is. By default it will change pixel values if the algorithm feels like it. Commented Mar 9, 2022 at 18:41

1 Answer 1

0

My humble guess as I don't have the input file to try is that you are relying on some default parameter when writing the ou.jp2 file.

could you try to copy all the metadata when writing the file instead:

with rasterio.open('/tmp/in.jp2') as infile:

    kwargs = infile.profile.copy()

    with rasterio.open('/tmp/out.jp2', 'w', **kwargs) as outfile:
        outfile.write(infile.read())

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.