GDAL-Image to numpy

本文介绍两种处理多波段遥感图像的方法,包括使用GDAL库将图像转换为NumPy数组,以及如何通过GDAL读取图像并进行保存。这两种方法适用于不同波段数量的图像,并提供了详细的Python代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考:http://gdal.org/python/


1、方法一

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import numpy as np
import os
import gdal
import sys

'''
# 多波段图像(遥感图像)提取每个波段信息转换成数组(波段数>=4 或者 波段数<=3)
# 一般的方法如:opencv,PIL,skimage 最多只能读取3个波段
# path 图像的路径
# return: 图像数组
'''
def Multiband2Array(path):

    src_ds = gdal.Open(path)
    if src_ds is None:
        print('Unable to open %s'% path)
        sys.exit(1)

    xcount=src_ds.RasterXSize # 宽度
    ycount=src_ds.RasterYSize # 高度
    ibands=src_ds.RasterCount # 波段数

    # print "[ RASTER BAND COUNT ]: ", ibands
    for band in range(ibands):
        band += 1
        # print "[ GETTING BAND ]: ", band
        srcband = src_ds.GetRasterBand(band) # 获取该波段
        if srcband is None:
            continue

        # Read raster as arrays 类似RasterIO(C++)
        dataraster = srcband.ReadAsArray(0, 0, xcount, ycount).astype(np.float32) # 这里得到的矩阵大小为 ycount x xcount
        if band==1:
            data=dataraster.reshape((ycount,xcount,1))
        else:
            # 将每个波段的数组很并到一个3维数组中
            data=np.append(data,dataraster.reshape((ycount,xcount,1)),axis=2)

    src_ds=None
    return data



if __name__=="__main__":
    cwd = os.getcwd()  # 返回脚本文件所在的工作目录
    path = os.path.join(cwd, '10.tif')
    path=r"F:\PL\2_1.tif"
    img=Multiband2Array(path)
    print(img.shape)
    # img = img.resize((28, 28,3))

    img_raw = img.tobytes()  # 将图片转化为原生bytes

    pass

2、方法二

import cv2
import numpy as np
from osgeo import gdal

filename="D:/cloud.tif"
ds = gdal.Open(filename)
data = ds.ReadAsArray()
# print(type(data))
# print(data.shape) #[c,h,w]
c,h,w=data.shape

raster_fn="_mask.tif"

target_ds = gdal.GetDriverByName('GTiff').Create(raster_fn, w, h, c, gdal.GDT_Byte)
target_ds.WriteRaster(0,0,w,h,data.tobytes()) # 保存
target_ds.FlushCache()
ds=None
target_ds=None

3、补充

# 读取数据转成numpy
data = ds.ReadAsArray()
# 或
data=ds.ReadRaster(0, 0, xcount2, ycount2)
data= np.fromstring(data, np.uint8)
data = np.reshape(data, [ycount2, xcount2]).astype(data_type)

# 按波段读取
srcband = src_ds.GetRasterBand(band)
data=srcband.ReadAsArray(0, 0, xcount2, ycount2).astype(data_type)

# 或
G2 = srcband.ReadRaster(0, 0, xcount2, ycount2)
G2 = np.fromstring(G2, np.uint8)
G2 = np.reshape(G2, [ycount2, xcount2]).astype(data_type)
# 保存数据
target_ds.WriteRaster(0,0,w,h,data.tobytes()) # 保存

# 按波段保存
target_ds.GetRasterBand(1).WriteArray(img, 0, 0)
# 或
target_ds.GetRasterBand(1).WriteRaster(0,0,xcount1,ycount1,img.tobytes())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值