numy array的取出和保存给其他array

numy array的取出和保存给其他array

1 基础

import os
import rasterio 
import numpy as np

"读取带有地理坐标的栅格影像"
def ReadRaster(raster, src_meta=True):
    """
    读取遥感影像数据.  parameters——raster:遥感影像的路径
    return——image: 遥感影像包含的array, src_meta: 遥感影像的坐标
    src_meta: 如果为True, 则读取坐标, 如果为False, 则不读取坐标
    """
    with rasterio.open(raster) as src:
        image = src.read()
        if image.shape[0] == 1:
            image = np.squeeze(image)
        if src_meta:
            src_meta = src.meta
        else:
            src_meta = None
    return image, src_meta

images_dir = r"\caImgs_10"
imgPath = os.path.join(images_dir,'001.tif')

"读取影像数据"
img, _ = ReadRaster(imgPath, src_meta=False)
img_size = img.shape
# (40, 512, 512)
# 影像是时间序列影像,shape为(4,512,512),共有10期;为了方便保存,我将所有时间的影像按照波段叠加保存到一起,因而一个时间序列影像的shape为(40,512,512)

"接下来要将shape为(40,512,512)的一个时间序列影像数据改变为shape(10,512,512,4)的数据"
frame_num = img_size[0] // 4  # frame是时间序列影像的时间序列数,4是波段数
# 10
img_size = (frame_num, ) + img_size[1:3] + (4, )
# (10, 512, 512, 4)

"rasterio读出来的默认shape是(band,height,width),但是matplotlib和keras的读取shape都是(height,width,band)"
img = img.transpose(1,2,0) 
# img.shape  (512, 512, 40)

"新建一个四维(包含帧数)的值为0的数组"
img_frame = np.zeros(img_size, dtype="uint16")  
# img_frame.shape (10, 512, 512, 4)

"注意下面三者的不同"
"1"
for f in range(frame_num):
    print(f)  
    print(img[:,:,f*4:f*4+4].shape)  # (512, 512, 4)
    img_frame[f,:,:,:] = img[:,:,f*4:f*4+4]
# 按理说正确,但是可能会报错,如果报错,可用下面两种方法解决 
"2"
for f in range(frame_num):
    print(f)
    print(np.expand_dims(img[:,:,f*4:f*4+4],0).shape)  # (1, 512, 512, 4)
    img_frame[f,:,:,:] = np.expand_dims(img[:,:,f*4:f*4+4],0)3for f in range(frame_num):
    print(f)
    img_band = img[:,:,f*4:f*4+4]
    print(img_band.shape)
    img_frame[f,:,:,:] = img_band

2 对原array作两个维度的遍历,并转存值

"还是使用上面读出来的array"
"这里要将原array中的原数据类型转换为uint8"
"方法为,先对原array作百分比截断,得到新的最大最小值,然后用最大最小值归一化法作归一化,再乘以255来作缩放"
compress_data = np.zeros((10,512,512,4), dtype="uint8")

for f in range(frame_num):  # 遍历frame帧数
    for b in range(4):  # 遍历band 波段数
        # 得到百分比对应的值
        data_band = img_frame[f,:,:,b]
        print(data_band.shape)  # (512, 512)
        cutmin = np.percentile(data_band, 2)
        cutmax = np.percentile(data_band, 98)
        data_band = np.clip(data_band,cutmin,cutmax)
        compress_data[f,:,:,b] = np.around((data_band - cutmin) * 255 / (cutmax - cutmin))
# 实质上是,先获取原始数据的2和98分位值,然后用这两个值对原始数据做截断,得到的新数据的最小值就是原始数据的2分位值,最大值就是原
# 始数据的98分位值.然后新数据用最大最小值归一化法做归一化,使得新数据的数值范围在[0,1]之间,因而需要再乘以255进行缩放.
# 以使得array中的不同值的差异更大来使得显示效果更好,从而获得uint8数据. 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值