import cv2
import numpy as np
img = cv2.imread("./1.png")
print(img.shape)
# out: (359, 299, 3)
# opencv-python读取数据——通道/波段在最后
cv2.imwrite(('./2.png'),img)
# out:True
img_1 = np.transpose(img, (2, 0, 1))
print(img_1.shape)
# out: (3, 359, 299)
cv2.imwrite(('./3.png'),img_1)
# out: 报错
opencv-python读取文件的shape格式为(row,col,channel),通道数在最后。写入文件时的array shape和读取文件的一样,也必须保证通道数在最后。
# 此处为sentinel2 3波段影像
import rasterio
import numpy as np
raster = rasterio.open("./L2A20190813N0213R113.tif")
red,green,blue = raster.read(1),raster.read(2),raster.read(3)
# 也可以用 bands = raster.read() 直接将三个波段数组一次读取
bands = raster.read()
print(bands.shape)
# out:(3, 10980, 10980)
# rasterio读取数据——通道/波段在最前面
print(red.shape,green.shape,blue.shape)
# out: ((10980, 10980), (10980, 10980), (10980, 10980))
nrg_new = np.stack([red,green,blue],axis=0)
print(nrg_new.shape)
# out:(3, 10980, 10980)
with rasterio.open(
'./1.tif',
'w',
driver='GTiff',
height=nrg_new.shape[1],
width=nrg_new.shape[2],
count=3,
dtype=nrg_new.dtype,
crs=raster.crs,
transform=raster.transform,
) as dst:
dst.write(nrg_new)
# out: 成功
nrg_1 = np.stack([red,green,blue],axis=2)
print(nrg_1.shape)
# out:(10980, 10980, 3)
with rasterio.open(
'./2.tif',
'w',
driver='GTiff',
height=nrg_new.shape[1],
width=nrg_new.shape[2],
count=3,
dtype=nrg_new.dtype,
crs=raster.crs,
transform=raster.transform,
) as dst:
dst.write(nrg_1)
# out: ValueError: Source shape (10980, 10980, 3) is inconsistent with given indexes 3
rasterio读取文件的shape格式为(channel,row,col),通道数在最前。写入文件时的array shape和读取文件的一样,也必须保证通道数在最前。
rasterio和opencv-python读取得到的数组都是行在前,列在后,尤其是当读取单通道/单波段数据时,shape为(row,col)。或者说numpy array默认shape格式就是(row,col)。rasterio和opencv-python读取/写入 数组的差别在于 rasterio通道数在前, opencv-python通道数在后。