微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

光栅:结合下采样和上采样

如何解决光栅:结合下采样和上采样

我需要先使用 average 重采样方法栅格数据集进行下采样,然后使用 bilinear 重采样方法对结果进行上采样。

理想情况下,我希望一次性完成 - 无需将任何数据写入磁盘。

到目前为止,我最好的解决方案是在初始读取时进行平均重采样,将结果写入 MemoryFile,然后在最终写入结果之前对 MemoryFile 的读取进行第二次重采样到磁盘。

我想知道是否有更好的方法来做到这一点?

这是一些可重现的代码

import numpy as np
import Rasterio as rio
from Rasterio.io import MemoryFile
from Rasterio.enums import resampling

src_profile = {
    "driver": "GTiff","dtype": "uint8","height": 1440,"width": 2880,"count":1,"nodata":255,}

with rio.open('sample.tif',"w",**src_profile) as dataset:
    
    shape = (src_profile["height"],src_profile["width"])
    # random data
    arr = np.arange(np.prod(shape),dtype="uint8").reshape(shape)
    dataset.write(arr,1)


with rio.open('sample.tif',"r") as dataset:
    
    rescale_factor = 0.25
    
    # avg resample on initial read
    data = dataset.read(
        out_shape=(
            dataset.count,int(dataset.height * rescale_factor),int(dataset.width * rescale_factor)
        ),resampling=resampling.average
    )

    tmp_profile = src_profile.copy()
    tmp_profile.update({
        "width": data.shape[-1],"height": data.shape[-2],})
    
    rescale_factor = 10
    
# write to memfile
with MemoryFile() as memfile:
    with memfile.open(**tmp_profile) as tempds:
        tempds.write(data)

        # read back with resample
        data = tempds.read(
            out_shape=(
                dataset.count,int(tmp_profile["height"] * rescale_factor),int(tmp_profile["width"] * rescale_factor)
            ),resampling=resampling.bilinear
        )

dst_profile = tmp_profile.copy()
dst_profile.update({
    "width": data.shape[-1],})

# write to disk
with rio.open('target.tif',**dst_profile) as dataset:
    dataset.write(data)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。