GID数据集8bit问题数据复查

有人针对昨天的留意说:GID5数据集中的8bit那个版本数据本身没有问题,软件显示错误是其读取方式带来的,如果代码读取是没问题的。

本着求真的精神,严肃讨论GID5数据集8BIT是否是问题数据。

本文框架如下:
1.代码读取影像,显示。

2.打断点显示第四波段。

3.对照组是代码显示16bit数据。

本次测试数据源自GID5 的GF2_PMS1__L1A0001680858-MSS1.tif

测试数据:8bit、16bit

代码如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
读取两张 4 波段 TIF,各取第 2、3、4 波段作为 RGB,并排同时显示。
"""

import numpy as np
from osgeo import gdal
import matplotlib.pyplot as plt

gdal.UseExceptions()


def read_rgb(tif_path, bands=(2, 3, 4), max_size=2000, stretch=(2, 98)):
    """
    读取影像并转成可以 imshow 的 uint8 RGB 数组。

    返回 (rgb, (out_w, out_h))
    """
    ds = gdal.Open(tif_path, gdal.GA_ReadOnly)
    if ds is None:
        raise IOError(f"无法打开影像:{tif_path}")

    if max(bands) > ds.RasterCount:
        raise ValueError(f"影像只有 {ds.RasterCount} 个波段,无法取 {bands}")

    W, H = ds.RasterXSize, ds.RasterYSize

    scale = max(1, int(np.ceil(max(W, H) / max_size)))
    out_w = max(1, W // scale)
    out_h = max(1, H // scale)

    rgb = np.zeros((out_h, out_w, 3), dtype=np.uint8)

    for i, b in enumerate(bands):
        band = ds.GetRasterBand(b)
        arr = band.ReadAsArray(0, 0, W, H, out_w, out_h).astype(np.float32)

        nd = band.GetNoDataValue()
        m = np.isfinite(arr)
        if nd is not None:
            m &= (arr != nd)

        if m.any():
            lo, hi = np.percentile(arr[m], stretch)
            if hi <= lo:
                hi = lo + 1.0
            v = np.clip(arr, lo, hi)
            scaled = (v - lo) * (255.0 / (hi - lo))
            scaled[~m] = 0
            rgb[..., i] = np.clip(np.rint(scaled), 0, 255).astype(np.uint8)

    ds = None
    return rgb, (out_w, out_h)


def show_rgb_grid(items, max_size=2000, stretch=(2, 98), ncols=None,
                  figsize_per_image=7):
    """
    同时显示多张影像。

    items: [(path, bands, title), ...]
    """
    n = len(items)
    if ncols is None:
        ncols = n
    nrows = int(np.ceil(n / ncols))

    fig, axes = plt.subplots(
        nrows, ncols,
        figsize=(figsize_per_image * ncols, figsize_per_image * nrows),
        squeeze=False,
    )

    for idx, (path, bands, title) in enumerate(items):
        r, c = divmod(idx, ncols)
        ax = axes[r][c]
        try:
            rgb, _ = read_rgb(path, bands=bands,
                              max_size=max_size, stretch=stretch)
            ax.imshow(rgb)
            ax.set_title(title or f"{path}\nbands={bands}")
        except Exception as e:
            ax.text(0.5, 0.5, f"读取失败:\n{e}",
                    ha="center", va="center", transform=ax.transAxes,
                    fontsize=9, color="red")
            ax.set_title(title or path)
        ax.axis("off")

    # 如果 items 数量少于子图数,隐藏多余子图
    for idx in range(n, nrows * ncols):
        r, c = divmod(idx, ncols)
        axes[r][c].axis("off")

    plt.tight_layout()
    plt.show()


if __name__ == "__main__":
    tif_8bit = r"E:\test\GF2_PMS1__L1A0001680858-MSS1.tif"
    tif_16bit = r"E:\test\GF2_PMS1__L1A0001680858-MSS1.tiff"

    items = [
        (tif_8bit,  (2, 3, 4), "8-bit"),
        (tif_16bit, (3, 2, 1), "16-bit"),
    ]

    show_rgb_grid(items, max_size=2000, stretch=(2, 98), ncols=2)

显示结果是

8bit和16bit的显示结果

现在在pycharm打断点检查影像数值。

8bit的第2波段的单通道显示如下:

8bit的第2波段的单通道显示

8bit的第4波段的单通道显示如下:

8bit的第4波段的单通道显示

昨天的结论是8bti是有问题的,第四波段是全255。今天的测试验证了昨天的结论。

今天还发现,部分 GID5 的 16 位数据在真彩色合成显示时存在异常:裸地区域偏紫,与常见的真彩色效果不符。6bit存在异常显示

随后我检索到一份他人已切片完成的 GID5 数据,大小约 18 GB,后续可直接使用这份现成数据,省去自行处理。

飞桨上的GID5