def rasterRW(fn, raster_lyr, raster_pred, raster_lyr_w):
    gdal.UseExceptions()
    '''打开栅格数据'''
    try:
        src_ds = gdal.Open(os.path.join(fn, raster_lyr))
    except RuntimeError as e:
        print('Unable to open %s' % os.path.join(fn, raster_lyr))
        print(e)
        sys.exit(1)
    print("metadata:", src_ds.GetMetadata())
    '''初始化输出栅格'''
    driver = gdal.GetDriverByName('GTiff')
    print(src_ds.RasterXSize, src_ds.RasterYSize)
    out_raster = driver.Create(os.path.join(fn, raster_lyr_w), col, row, 1,
                               gdal.GDT_Float64)
    #    out_raster=driver.Create(os.path.join(fn,raster_lyr_w),row,col,1,gdal.GDT_CInt16)
    out_raster.SetProjection(src_ds.GetProjection())  #设置投影与参考栅格同
    out_raster.SetGeoTransform(src_ds.GetGeoTransform())  #配置地理转换与参考栅格同
    '''将数组传给栅格波段,为栅格值'''
    out_band = out_raster.GetRasterBand(1)
    out_band.WriteArray(raster_pred)
    '''设置overview'''
    overviews = pb.compute_overview_levels(out_raster.GetRasterBand(1))
    out_raster.BuildOverviews('average', overviews)
    '''清理缓存与移除数据源'''
    out_band.FlushCache()
    out_band.ComputeStatistics(False)
    del src_ds, out_raster, out_band
def rasterCal(fn, raster_lyr, raster_lyr_w):
    gdal.UseExceptions()
    '''打开栅格数据'''
    try:
        src_ds = gdal.Open(os.path.join(fn, raster_lyr))
    except RuntimeError as e:
        print('Unable to open %s' % os.path.join(fn, raster_lyr))
        print(e)
        sys.exit(1)
    print("metadata:", src_ds.GetMetadata())
    '''获取所有波段'''
    srcband = []
    for band_num in range(1, 8):
        try:
            srcband.append(src_ds.GetRasterBand(band_num))
        except RuntimeError as e:
            print('Band ( %i ) not found' % band_num)
            print(e)
            sys.exit(1)
    print(srcband)
    '''获取用于NDVI计算的红和近红波段数组,并计算ndvi'''
    red = srcband[3].ReadAsArray().astype(np.float)
    nir = srcband[4].ReadAsArray()
    red = np.ma.masked_where(nir + red == 0, red)  #确定分母不为零
    ndvi = (nir - red) / (nir + red)
    ndvi = ndvi.filled(-99)
    print(ndvi.shape, ndvi.std(), ndvi.max(), ndvi.min(), ndvi.mean())
    '''初始化输出栅格'''
    driver = gdal.GetDriverByName('GTiff')
    if os.path.exists(os.path.join(fn, raster_lyr_w)):
        driver.Delete(os.path.join(fn, raster_lyr_w))
    out_raster = driver.Create(os.path.join(fn,
                                            raster_lyr_w), src_ds.RasterXSize,
                               src_ds.RasterYSize, 1, gdal.GDT_Float64)
    out_raster.SetProjection(src_ds.GetProjection())  #设置投影与参考栅格同
    out_raster.SetGeoTransform(src_ds.GetGeoTransform())  #配置地理转换与参考栅格同
    '''将数组传给栅格波段,为栅格值'''
    out_band = out_raster.GetRasterBand(1)
    out_band.WriteArray(ndvi)
    '''设置overview'''
    overviews = pb.compute_overview_levels(out_raster.GetRasterBand(1))
    out_raster.BuildOverviews('average', overviews)
    '''清理缓存与移除数据源'''
    out_band.FlushCache()
    out_band.ComputeStatistics(False)
    del src_ds, out_raster, out_band
    return ndvi
Exemplo n.º 3
0
# Script to compute NDVI.

import os
import numpy as np
from osgeo import gdal
import ospybook as pb

os.chdir(r'D:\osgeopy-data\Massachusetts')
in_fn = 'm_4207162_ne_19_1_20140718_20140923.tif'
out_fn = 'ndvi2.tif'

ds = gdal.Open(in_fn)
red = ds.GetRasterBand(1).ReadAsArray().astype(np.float)
nir = ds.GetRasterBand(4).ReadAsArray()

# Mask the red band.
red = np.ma.masked_where(nir + red == 0, red)

# Do the calculation.
ndvi = (nir - red) / (nir + red)

# Fill the empty cells.
ndvi = ndvi.filled(-99)

# Set NoData to the fill value when creating the new raster.
out_ds = pb.make_raster(ds, out_fn, ndvi, gdal.GDT_Float32, -99)

overviews = pb.compute_overview_levels(out_ds.GetRasterBand(1))
out_ds.BuildOverviews('average', overviews)
del ds, out_ds
folder = r"D:\osgeopy-data\Landsat\Utah"
raster_fns = ["LE70380322000181EDC02_60m.tif", "LE70380322000181EDC02_TIR_60m.tif"]
out_fn = "kmeans_prediction_60m.tif"

# Function from list 10.10.
def stack_bands(filenames):
    """Returns a 3D array containing all band data from all files."""
    bands = []
    for fn in raster_fns:
        ds = gdal.Open(fn)
        for i in range(1, ds.RasterCount + 1):
            bands.append(ds.GetRasterBand(i).ReadAsArray())
    return np.dstack(bands)


# Stack the bands and run the analysis.
os.chdir(folder)
data = pb.stack_bands(raster_fns)
classes, centers = spectral.kmeans(data)

# Save the output.
ds = gdal.Open(raster_fns[0])
out_ds = pb.make_raster(ds, out_fn, classes, gdal.GDT_Byte)
levels = pb.compute_overview_levels(out_ds.GetRasterBand(1))
out_ds.BuildOverviews("NEAREST", levels)
out_ds.FlushCache()
out_ds.GetRasterBand(1).ComputeStatistics(False)

del out_ds, ds
Exemplo n.º 5
0
data = pb.stack_bands(raster_fns)

# Sample the satellite data at the coordinates from the csv.
sample = data[rows, cols, :]

# Fit the classification tree.
clf = tree.DecisionTreeClassifier(max_depth=5)
clf = clf.fit(sample, classes)

# Apply the new classification tree model to the satellite data.
rows, cols, bands = data.shape
data2d = np.reshape(data, (rows * cols, bands))
prediction = clf.predict(data2d)
prediction = np.reshape(prediction, (rows, cols))

# Set the pixels with no valid satellite data to 0.
prediction[np.sum(data, 2) == 0] = 0

# Save the output.
predict_ds = pb.make_raster(ds, out_fn, prediction, gdal.GDT_Byte, 0)
predict_ds.FlushCache()
levels = pb.compute_overview_levels(predict_ds.GetRasterBand(1))
predict_ds.BuildOverviews('NEAREST', levels)

# Apply the color table from the SWReGAP landcover raster.
gap_ds = gdal.Open(gap_fn)
colors = gap_ds.GetRasterBand(1).GetRasterColorTable()
predict_ds.GetRasterBand(1).SetRasterColorTable(colors)

del ds
Exemplo n.º 6
0
def rasterR(fn, raster_lyr, raster_lyr_w, bandNum):
    gdal.UseExceptions()
    '''打开栅格数据'''
    try:
        src_ds = gdal.Open(os.path.join(fn, raster_lyr))
    except RuntimeError as e:
        print('Unable to open %s' % os.path.join(fn, raster_lyr))
        print(e)
        sys.exit(1)
    print("metadata:", src_ds.GetMetadata())
    '''获取所有波段'''
    srcband = []
    for band_num in range(1, bandNum + 1):
        try:
            srcband.append(src_ds.GetRasterBand(band_num))
        except RuntimeError as e:
            print('Band ( %i ) not found' % band_num)
            print(e)
            sys.exit(1)
    print(srcband)
    '''获取RGB并图表打印查看'''
    rsData = {}
    for key in range(bandNum):
        rsData[key] = srcband[key].ReadAsArray().astype(np.int32)
    for key in range(bandNum):
        print(rsData[key].shape)
        print(DataFrame(rsData[key].flatten()).describe()
              )  #count数量/mean均值/std标准差/min最小值/25%下四分位/50%中位数/75%上四分位/max最大值

    rgb = np.stack((rsData[0], rsData[1], rsData[2]), axis=2)
    #    rgb[rgb==256]=100 #如果有些值不正确,或者需调整某些值时,可以进行替换
    #    print(rgb)

    fig = plt.figure(figsize=(20, 12))
    ax = fig.add_subplot(111)
    ax.imshow(rgb)
    plt.show()
    print(rgb)
    print(rgb.shape)
    '''将RGB转换为HSV,并图表打印查看'''
    vfunc = np.vectorize(
        colorsys.rgb_to_hsv)  # HSV代表色调(Hue),饱和度(Saturation)和值(Value)
    #    vfunc=np.vectorize(colorsys.rgb_to_hls)  # HSL代表色调(Hue),饱和度(Saturation)和亮度(Lightness)
    H, S, V = vfunc(rsData[0], rsData[1], rsData[2])
    HSV = np.stack((H, S, V), axis=2)
    print(HSV)
    print(HSV.shape)
    #HSV = cv2.cvtColor(rgb, cv2.COLOR_BGR2HSV)
    #    print(HSV.T.shape)
    print(DataFrame(H.flatten()).describe())

    fig = plt.figure(figsize=(20, 12))
    ax = fig.add_subplot(111)
    ax.imshow(HSV)
    plt.show()
    '''将单独的色彩向量写入栅格,此次写入的是H色调值'''
    '''初始化输出栅格'''
    driver = gdal.GetDriverByName('GTiff')
    out_raster = driver.Create(os.path.join(fn,
                                            raster_lyr_w), src_ds.RasterXSize,
                               src_ds.RasterYSize, 1, gdal.GDT_Float64)
    out_raster.SetProjection(src_ds.GetProjection())  #设置投影与参考栅格同
    out_raster.SetGeoTransform(src_ds.GetGeoTransform())  #配置地理转换与参考栅格同
    '''将数组传给栅格波段,为栅格值'''
    out_band = out_raster.GetRasterBand(1)
    H[H > 0.9] = 0.01  #根据情况调整色调值,或进行标识
    H[H == 0] = 1  #特殊值处理,例如空白的值
    out_band.WriteArray(1 - H)
    #    out_band.WriteArray(V) #也可自行尝试写入其它值
    '''设置overview,本部分未使用'''
    overviews = pb.compute_overview_levels(out_raster.GetRasterBand(1))
    overviews = pb.compute_overview_levels(srcband[0])
    src_ds.BuildOverviews('average', overviews)
    '''清理缓存与移除数据源'''
    out_band.FlushCache()
    out_band.ComputeStatistics(False)
    del src_ds, out_raster, out_band

    return rsData