numy array的取出和保存给其他array
- 1 基础
- 2 对原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
"接下来要将shape为(40,512,512)的一个时间序列影像数据改变为shape(10,512,512,4)的数据"
frame_num = img_size[0] // 4
img_size = (frame_num, ) + img_size[1:3] + (4, )
"rasterio读出来的默认shape是(band,height,width),但是matplotlib和keras的读取shape都是(height,width,band)"
img = img.transpose(1,2,0)
"新建一个四维(包含帧数)的值为0的数组"
img_frame = np.zeros(img_size, dtype="uint16")
"注意下面三者的不同"
"1"
for f in range(frame_num):
print(f)
print(img[:,:,f*4:f*4+4].shape)
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)
img_frame[f,:,:,:] = np.expand_dims(img[:,:,f*4:f*4+4],0)
”3“
for 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):
for b in range(4):
data_band = img_frame[f,:,:,b]
print(data_band.shape)
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))