def World2Pixel(geoMatrix, x, y):
    #使用gdal库的geomatrix对象【gdal.GetGeoTransform()】计算地理坐标的像素位置
    ulX = geoMatrix[0]
    ulY = geoMatrix[3]
    xDist = geoMatrix[1]
    yDist = geoMatrix[5]
    pixel = int((x - ulX) / xDist)
    line = int((ulY - y) / abs(yDist))
    return (pixel, line)


raster = r"D:\Program Files\Python学习文档\samples\FalseColor\stretched.tif"
shp = r"D:\Program Files\Python学习文档\samples\hancock\hancock.shp"
output = r"D:\Program Files\Python学习文档\samples\FalseColor\clip3.tif"
srcArray = gdal_array.LoadFile(raster)
#同时载入gdal库的图片从而获取geotransform(世界文件)
srcImage = gdal.Open(raster)
geoTrans = srcImage.GetGeoTransform()
reader = shapefile.Reader(shp)
#将图层扩张转化为图片像素坐标
minX, minY, maxX, maxY = reader.bbox
ulX, ulY = World2Pixel(geoTrans, minX, maxY)
lrX, lrY = World2Pixel(geoTrans, maxX, minY)
#计算新图片的像素尺寸
pxWidth = int(lrX - ulX)
pxHeight = int(lrY - ulY)
clip = srcArray[:, ulY:lrY, ulX:lrX]
#为图片创建一个新的geomatrix对象以便附加地理参考数据
geoTrans = list(geoTrans)
geoTrans[0] = minX
示例#2
0
                    type=str,
                    required=True,
                    help='the title of the image')
parser.add_argument('--output',
                    '-o',
                    type=str,
                    required=True,
                    help='the output image file')
args = parser.parse_args()
true_file = args.true.expanduser()
pred_file = args.predict.expanduser()
band_ix = args.band
title = args.title
output_name = args.output

ix = gdal_array.LoadFile(str(true_file))
iy = gdal_array.LoadFile(str(pred_file))

if ix.ndim == 3:
    ix = ix[band_ix]
    iy = iy[band_ix]
# 单波段数据
assert ix.ndim == 2 and iy.ndim == 2

x = ix[:500, :500].flatten()
y = iy[:500, :500].flatten()
r2 = r2_score(x, y)

xy = np.vstack([x, y])
z = gaussian_kde(xy)(xy)
idx = z.argsort()
示例#3
0
"""Perform a simple difference image change detection on a
'before' and 'after' image."""

# Before image: http://git.io/vqa6h
# After image: http://git.io/vqaic

from osgeo import gdal, gdal_array
import numpy as np

# "Before" image
im1 = "before.tif"
# "After" image
im2 = "after.tif"
# Load before and after into arrays
ar1 = gdal_array.LoadFile(im1).astype(np.int8)
ar2 = gdal_array.LoadFile(im2)[1].astype(np.int8)
# Perform a simple array difference on the images
diff = ar2 - ar1
# Set up our classification scheme to try
# and isolate significant changes
classes = np.histogram(diff, bins=5)[1]
# The color black is repeated to mask insignificant changes
lut = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 255, 0], [255, 0, 0]]
# Starting value for classification
start = 1
# Set up the output image
rgb = np.zeros((
    3,
    diff.shape[0],
    diff.shape[1],
), np.int8)
        t.up()
        t.goto(x - 15, y - 6)
        t.write("{}".format((i * label)), align="right")
    x_ratio = 709.0 / 256
    y_ratio = 450.0 / pixels
    colors = ["red", "green", "blue"]
    for j in range(len(hist)):
        h = hist[j]
        x = -354
        y = -199
        t.up()
        t.goto(x, y)
        t.down()
        t.color(colors[j])
    for i in range(256):
        x = i * x_ratio
        y = h[i] * y_ratio
        x = x - (709 / 2)
        y = y + -199
        t.goto((x, y))


img = "22333.tif"
histograms = []
arr = gdal_array.LoadFile(img)
for b in arr:
    histograms.append(histogram(b))
    draw_histogram(histograms)
    t.pen(shown=False)
    t.done
示例#5
0
def histogram(a, bins=list(range(0, 256))):
    fa = a.flat
    n = gdal_array.numpy.searchsorted(gdal_array.numpy.sort(fa), bins)
    n = gdal_array.numpy.concatenate([n, [len(fa)]])
    hist = n[1:] - n[:-1]
    return hist


def stretch(a):
    #在gdal_array上传的图像数组中执行直方图均衡化操作
    hist = histogram(a)
    lut = []
    for b in range(0, len(hist), 256):
        #步长尺寸
        step = reduce(operator.add, hist[b:b + 256]) / 256
        #创建均衡的查找表
        n = 0
        for i in range(256):
            lut.append(n / step)
            n = n + hist[i + b]
    gdal_array.numpy.take(lut, a, out=a)
    return a


src = r"D:\Program Files\Python学习文档\samples\FalseColor\Swap.tif"
array = gdal_array.LoadFile(src)
stretched = stretch(array)
output = r"D:\Program Files\Python学习文档\samples\FalseColor\stretched.tif"
output = gdal_array.SaveArray(array, output, format="GTiff", prototype=src)
output = None
示例#6
0
Fading = os.path.join('/cygdrive', 'f', 'Fading', 'Tiles', 'Fade')
outdir = os.path.join('/cygdrive', 'f', 'Fading', 'Fade_Merge', 'Netherlands')

rawTiles = os.listdir(bkgd)
rawTiles = [f for f in rawTiles if f.endswith('.tif')]

#closes the raster data set

for bkgdTile in rawTiles:
    print bkgdTile
    ctTile = os.path.join(country, 'Neth_' + bkgdTile)
    fadeIn = os.path.join(Fading, 'FadeIn_' + bkgdTile)
    fadeOut = os.path.join(Fading, 'FadeOut_' + bkgdTile)

    print ctTile, fadeIn, fadeOut
    fadeInArr = gdal_array.LoadFile(fadeIn)
    fadeOutArr = gdal_array.LoadFile(fadeOut)
    ctArr = gdal_array.LoadFile(ctTile)
    bkgdArr = gdal_array.LoadFile(os.path.join(bkgd, bkgdTile))

    #get all raster information from sample raster
    raster = gdal.Open(ctTile)
    ys = raster.RasterYSize  #rows
    xs = raster.RasterXSize  #cols
    band = raster.GetRasterBand(1)
    ndvC = band.GetNoDataValue()
    tr = raster.GetGeoTransform()
    pr = raster.GetProjection()
    xOrigin = tr[0]
    yOrigin = tr[3]
    pixelWidth = tr[1]
示例#7
0
def img_classify(source, target):
    ''' img_classify() - Classify a remotely sensed image
    
    Parameters
    ----------
    source : str
        imput image file name

    target : str
        output file name

    Returns
    -------
    nothing

    '''
    from osgeo import gdal_array as gdal_array

    srcArr = gdal_array.LoadFile(source)  # Load the image into numpy using gdal
    
    # Split the histogram into 20 bins as our classes
    classes = gdal_array.numpy.histogram(srcArr, bins=20)[1]

    # Color look-up table (LUT) - must be len(classes)+1, specified as R, G, B tuples
    lut = [
        [255, 0, 0],
        [191, 48, 48],
        [166, 0, 0],
        [255, 64, 64],
        [255, 115, 115],
        [255, 116, 0],
        [191, 113, 48],
        [255, 178, 115],
        [0, 153, 153],
        [29, 115, 115],
        [0, 99, 99],
        [166, 75, 0],
        [0, 204, 0],
        [51, 204, 204],
        [255, 150, 64],
        [92, 204, 204],
        [38, 153, 38],
        [0, 133, 0],
        [57, 230, 57],
        [103, 230, 103],
        [184, 138, 0],
    ]
    start = 1  # Starting value for classification

    # Set up the RGB color JPEG output image
    rgb = gdal_array.numpy.zeros(
        (
            3,
            srcArr.shape[0],
            srcArr.shape[1],
        ),
        gdal_array.numpy.float32,
    )
    for i in range(len(classes)):  # Process all classes and assign colors
        mask = gdal_array.numpy.logical_and(start <= srcArr, srcArr <= classes[i])
        for j in range(len(lut[i])):
            rgb[j] = gdal_array.numpy.choose(mask, (rgb[j], lut[i][j]))
        start = classes[i] + 1

    # Save the image
    output = gdal_array.SaveArray(
        rgb.astype(gdal_array.numpy.uint8), target, format="JPEG"
    )
    output = None
    return
示例#8
0
#    else:
#        print('No exist nan value in {}'.format(image_name))
#        array2raster(image_name, ldata_array,
#                     xsize=x_size, ysize=y_size,
#                     transform=trans, projection=proj,
#                     dtype=gdal.GDT_Float32)
#    ldata_list.append(ldata_array)

"""MODIS sacle"""
for path in path_list:
    image_name = path.name
    #read img as array, method1
    #ldata = gdal.Open(str(path))
    #ldata_array =  ldata.ReadAsArray()
    #read img as array, method2
    ldata_array = gdal_array.LoadFile(str(path))
    ldata_array[ldata_array==0]=np.nan
    # replace 0 with nan.
#    # two methods to test nan values. method1:
#    # if np.isnan(ldata_array).sum>0:
#    # two methods to test nan values. method2:
    if np.where(np.isnan(ldata_array))[0].size>0:
        #np.where(ldata_array==0)#return row and column number of 0 value, start from 0.
        print('Exist 0 value in {}, Nan numbers: {}'.format(image_name,np.where(np.isnan(ldata_array))))
        ldata_array = pd.DataFrame(ldata_array)
#        #filling with mean value of column;https://blog.csdn.net/sinat_29957455/article/details/79017363
        ldata_array = ldata_array.fillna(ldata_array.mean())
        ldata_array = ldata_array.values
        array2raster(image_name, ldata_array,
                     xsize=x_size, ysize=y_size,
                     transform=trans, projection=proj,
# Numpy/gdal_array - Read an image, extract a band, save a new image

# https://github.com/GeospatialPython/Learning/raw/master/SatImage.zip

from osgeo import gdal_array
srcArray = gdal_array.LoadFile("SatImage.tif")
band1 = srcArray[0]
gdal_array.SaveArray(band1, "band1.jpg", format="JPEG")
示例#10
0
    prototype = gdal.Open(prototype)
    gdal_array.CopyDatasetInfo(prototype, ds, xoff=xoffset, yoff=yoffset)
    return ds


# Multispectral image used
# to create the NDVI. Must
# have red and infrared
# bands
source = "farm.tif"

# Output geotiff file name
target = "ndvi.tif"

# Load the source data as a gdal_array array
srcArray = gdal_array.LoadFile(source)

# Also load as a gdal image to
# get geotransform (world file) info
srcImage = gdal.Open(source)
geoTrans = srcImage.GetGeoTransform()

# Red and infrared (or near infrared) bands
r = srcArray[1]
ir = srcArray[2]

# Clip a field out of the bands using a
# field boundary shapefile

# Create an OGR layer from a Field boundary shapefile
field = ogr.Open("field.shp")
示例#11
0
# -*- coding: utf-8 -*-
"""
Created on Tue Feb  4 19:28:54 2020

@author: 立文
"""
#OpenImage.py 使用GDAL库打开栅格数据
from osgeo import gdal
from osgeo import gdal_array

raster = gdal.Open(
    r"D:\Program Files\Python学习文档\samples\SatImage\SatImage.tif")
print(raster.RasterCount)
print(raster.RasterXSize)
print(raster.RasterYSize)
srcArray = gdal_array.LoadFile(
    r"D:\Program Files\Python学习文档\samples\SatImage\SatImage.tif")
band1 = srcArray[0]
gdal_array.SaveArray(band1,
                     r"D:\Program Files\Python学习文档\samples\band1.jpg",
                     format="JPEG")
                                    width=5490,
                                    height=5490,
                                    outputType=gdal.GDT_Int16)
    for img in i:
        img_file = gdal.Open(img)
        gdal.Warp(str(img[0:25]) + '.tif', img_file, options=warp_options)

    df = pd.DataFrame(columns=[
        'B01', 'B02', 'B03', 'B04', 'B05', 'B06', 'B07', 'B08', 'B8A', 'B09',
        'B10', 'B11', 'B12'
    ])
    fileList = glob.glob(img[0:21] + '_B??.tif')

    print('writing reflectance values to dataframe...')
    for file in fileList:
        rasterArray = (gdal_array.LoadFile(file) * 0.0001)
        write_band = rasterArray.flatten()
        band_number = str(file[-7:-4])
        df[band_number] = write_band

    print('loading model...')
    model = load_model(path_to_model)  #path to .h5 model

    t3 = time.time()
    print('predicting...')
    y_pred = model.predict(df.values)
    t4 = time.time()
    Total = round((t4 - t3) / 60, 1)
    print('Predictions complete, took ' + str(Total) + ' minutes.')
    print('Writing output raster...')
    y_pred_class = np.argmax(y_pred, axis=1)
示例#13
0
 def loadTifInstance(self, path):
     return gdal_array.LoadFile(path)