コード例 #1
0
ファイル: magphase.py プロジェクト: pciphelippeneveu/gdal-1
def doit(src_filename, dst_magnitude, dst_phase):
    src_ds = gdal.Open(src_filename)
    xsize = src_ds.RasterXSize
    ysize = src_ds.RasterYSize
    print('{} x {}'.format(xsize, ysize))

    src_image = src_ds.GetRasterBand(1).ReadAsArray()
    mag_image = pow(
        numpy.real(src_image) * numpy.real(src_image) +
        numpy.imag(src_image) * numpy.imag(src_image), 0.5)
    gdalnumeric.SaveArray(mag_image, dst_magnitude)

    phase_image = numpy.angle(src_image)
    gdalnumeric.SaveArray(phase_image, dst_phase)
    return 0
コード例 #2
0
ファイル: image_extraction.py プロジェクト: tditt/ba_final
def retrieve_random_rectangles(size_deg=.5):
    # determines size of quadrants in degrees
    # offsets create a "padding" at the map edges which will not be used for retrieving images
    lon_area = max_lon - min_lon
    lat_area = max_lat - min_lat
    # create an array with the exact amount of elements needed
    lon_arr = np.zeros(int(math.floor(lon_area - 2 * lon_offset) / size_deg))
    # fill with valid lon-values (have to be divisible through size_deg and in between offsets)
    for i in range(0, lon_arr.shape[0]):
        lon_arr[i] = min_lon + lon_offset + i * size_deg
    # same thing for lat-values
    lat_arr = np.zeros(int(math.floor(lat_area - 2 * lat_offset) / size_deg))
    for i in range(0, lat_arr.shape[0]):
        lat_arr[i] = min_lat + lat_offset + i * size_deg
    # print("SHAPES: lon ", lon_arr.shape, " ||lat ", lat_arr.shape)
    # shuffle arrays as long as it takes
    np.random.shuffle(lon_arr)
    np.random.shuffle(lat_arr)
    while check_for_dupe_pairs(lat_arr, lon_arr):
        np.random.shuffle(lon_arr)
        np.random.shuffle(lat_arr)
    path = os.getcwd() + '\\resources\\training_north_pole\\' + str(int(math.floor(size_deg))) + '\\'
    # pick first xx items of the shuffled arrays and combine them to a coordinate
    max_pairs = lat_arr.shape[0] - 1

    for i in range(0, max_pairs):
        normalized_lon = str(lon_arr[i] + 180)
        normalized_lat = str(lat_arr[i] + 90)
        # output a square image with coordinate as the middle and size_deg*2 as side lengths
        file_name = str(
            str(i).zfill(2) + "_" + normalized_lat + "_" + normalized_lon + ".PNG")
        gdalnumeric.SaveArray(retrieve_crater([lon_arr[i], lat_arr[i]], [size_deg, 9], rotate=True), path + file_name,
                              format="PNG")
コード例 #3
0
def doit(src_filename, dst_filename):
    class_defs = [(1, 10, 20),
                  (2, 20, 30),
                  (3, 128, 255)]

    src_ds = gdal.Open(src_filename)
    xsize = src_ds.RasterXSize
    ysize = src_ds.RasterYSize

    src_image = gdalnumeric.LoadFile(src_filename)

    dst_image = numpy.zeros((ysize, xsize))

    for class_info in class_defs:
        class_id = class_info[0]
        class_start = class_info[1]
        class_end = class_info[2]

        class_value = numpy.ones((ysize, xsize)) * class_id

        mask = numpy.bitwise_and(
            numpy.greater_equal(src_image, class_start),
            numpy.less_equal(src_image, class_end))

        dst_image = numpy.choose(mask, (dst_image, class_value))

    gdalnumeric.SaveArray(dst_image, dst_filename)
コード例 #4
0
    def execute(self, args, line, interp):
        import gdalnumeric
        import gview

        data = args[0][0]
        dataname = args[0][1]
        fname = args[1]
        fmt = args[2]
        dataset = args[3]
        if dataset is not None:
            dataset = dataset[0]

        if data is None:
            interp.showText('No input variable supplied', 'error')
            return 0

        import Numeric
        if type(data) == type(Numeric.zeros([1, 1])):

            # Only array data should get to here
            if ((fmt is None) or (len(fmt) == 0)):
                fmt = 'GTiff'

            try:
                gdalnumeric.SaveArray(data, fname, fmt, dataset)
                return 1
            except ValueError:
                txt = fmt + ' format not available.  Available formats are:\n'
                import gdal
                for cDriver in gdal.GetDriverList():
                    txt = txt + cDriver.ShortName + ' '
                interp.showText(txt, 'error')

        else:
            try:
                if fmt is not None:
                    txt = 'Warning: format option is only available for rasters.\n'
                    txt=txt+'         '+fname+\
                    ' will be saved in shapefile format.'
                    interp.showText(txt, 'error')

                if data.save_to(fname) == 0:
                    interp.showText('Unable to save '+\
                                    dataname+' to file '+fname,'error')
                    return 0

                return 1
            except:
                interp.showText('Unable to save '+\
                                dataname+' to file '+fname,'error')
コード例 #5
0
ファイル: modis_tg_halli.py プロジェクト: xzk0010/hydrology
def process_modis(input_folder,
                  output_folder,
                  scale_factor=0.1,
                  null_value=32760,
                  file_extension='*.tif'):
    files_list = os.listdir(input_folder)
    for item in files_list:
        if fnmatch.fnmatch(item, file_extension):
            in_raster = input_folder + '/' + item
            in_raster = gdal.Open(in_raster, GA_ReadOnly)
            out_raster = output_folder + '/' + 'proc_' + item
            band1 = in_raster.GetRasterBand(1)
            in_array = BandReadAsArray(band1)
            in_array[in_array > null_value] = np.nan
            data_out = in_array * scale_factor
            gdalnumeric.SaveArray(data_out,
                                  filename=out_raster,
                                  format='GTiff',
                                  prototype=in_raster)
コード例 #6
0
ファイル: image_extraction.py プロジェクト: tditt/ba_final
def retrieve_all_craters(crater_layer):
    count = 0
    for crater in crater_layer:
        count += 1
        radius_km = crater.GetField("Radius_km")
        if radius_km > 10:
            geo_coord = [float(crater.GetField("Lon_E")), float(crater.GetField("Lat"))]
            if min_lon <= geo_coord[0] <= max_lon and min_lat <= geo_coord[1] <= max_lat:
                # if -60.0 < geo_coord[1] < 60.0: continue
                radius = [crater.GetField("Radius_deg"), radius_km]
                try:
                    rect = retrieve_crater(geo_coord, radius)
                    normalized_lon = str(geo_coord[0] + 180)
                    normalized_lat = str(geo_coord[1] + 90)
                    file_name = str(
                        str(count).zfill(5) + "_" + normalized_lat + "_" + normalized_lon + "_R" + str(
                            int(radius_km)) + ".jpeg")
                    path = os.getcwd() + '\\resources\\craters\\' + file_name
                    gdalnumeric.SaveArray(rect, path, format="JPEG")
                except:
                    print(count, geo_coord, radius, radius_km)
コード例 #7
0
"""Swap bands in a raster satellite image"""
# Module within the GDAL python package
import gdalnumeric
# name of our source image
src = "FalseColor.tif"
# load the source image into an array
arr = gdalnumeric.LoadFile(src)
# swap bands 1 and 2 for a natural color image.
# We will use numpy "advanced slicing" to reorder the bands.
# Using the source image
gdalnumeric.SaveArray(arr[[1, 0, 2], :],
                      "swap.tif",
                      format="GTiff",
                      prototype=src)
コード例 #8
0
tgt = "../dati/islands/islands_classified.jpg"

srcArr = gdalnumeric.LoadFile(src)

classes = gdalnumeric.numpy.histogram(srcArr, bins=2)[1]
print classes

#Color look-up table (LUT) - must be len(classes)+1.
#Specified as R,G,B tuples
lut = [[255, 0, 0], [0, 0, 0], [255, 255, 255]]

start = 1

rgb = gdalnumeric.numpy.zeros((
    3,
    srcArr.shape[0],
    srcArr.shape[1],
), gdalnumeric.numpy.float32)

# Process all classes and assign colors
for i in range(len(classes)):
    mask = gdalnumeric.numpy.logical_and(start <= srcArr, srcArr <= classes[i])
    for j in range(len(lut[i])):
        rgb[j] = gdalnumeric.numpy.choose(mask, (rgb[j], lut[i][j]))
    start = classes[i] + 1

# Save the image
gdalnumeric.SaveArray(rgb.astype(gdalnumeric.numpy.uint8),
                      tgt,
                      format="GTIFF",
                      prototype=src)
コード例 #9
0
ファイル: gda.py プロジェクト: OmPrakash95/Tearoscope
# Load the image into numpy using gdal
srcArr = gdalnumeric.LoadFile(src)

# Split the histogram into 20 bins as our classes
classes = gdalnumeric.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]]

# Starting value for classification
start = 1

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

# Save the image    
gdalnumeric.SaveArray(rgb.astype(gdalnumeric.numpy.uint8), 
tgt, format="JPEG")
コード例 #10
0
def histogram(a, bins=range(0, 256)):
    fa = a.flat
    n = gdalnumeric.numpy.searchsorted(gdalnumeric.numpy.sort(fa), bins)
    n = gdalnumeric.numpy.concatenate([n, [len(fa)]])
    hist = n[1:] - n[:1]
    return hist


def stretch(a):
    hist = histogram(a)
    print hist
    lut = []
    for b in range(0, len(hist), 256):
        step = reduce(operator.add, hist[b:b + 256]) / 255
        n = 0
        for i in range(256):
            lut.append(n / step)
            n = n + hist[i + b]
    gdalnumeric.numpy.take(lut, a, out=a)
    return a


src = "../dati/SatImage/swap.tif"
arr = gdalnumeric.LoadFile(src)
stretched = stretch(arr)
gdalnumeric.SaveArray(arr,
                      "../dati/SatImage/stretched.tif",
                      format="GTiff",
                      prototype=src)
コード例 #11
0
  """
    fa = a.flat
    n = gdalnumeric.numpy.searchsorted(gdalnumeric.numpy.sort(fa), bins)
    n = gdalnumeric.numpy.concatenate([n, [len(fa)]])
    hist = n[1:] - n[:-1]
    return hist


def stretch(a):
    """
  Performs a histogram stretch on a gdalnumeric array image.
  """
    hist = histogram(a)
    lut = []
    for b in range(0, len(hist), 256):
        # step size
        step = reduce(operator.add, hist[b:b + 256]) / 255
        # create equalization lookup table
        n = 0
        for i in range(256):
            lut.append(n / step)
            n = n + hist[i + b]
    gdalnumeric.numpy.take(lut, a, out=a)
    return a


src = "swap.tif"
arr = gdalnumeric.LoadFile(src)
stretched = stretch(arr)
gdalnumeric.SaveArray(arr, "stretched.tif", format="GTiff", prototype=src)
コード例 #12
0
    print("a %s") % a
    print("-----------")
    for b in a:
        print("%s") % b
    break
markers = np.zeros_like(image_array)
markers[image_array < 90] = 1
markers[image_array > 90] = 2
markers[image_array > 110] = 3

# print image_array
# print markers

segmentation = watershed(image_array, markers)
print segmentation
gdalnumeric.SaveArray(segmentation, dst_segmentation, format="GTiff")

# sobel
# im = scipy.misc.imread(dst)
# im = im.astype('int32')
# dx = ndimage.sobel(im, 0)  # horizontal derivative
# dy = ndimage.sobel(im, 1)  # vertical derivative
# mag = numpy.hypot(dx, dy)  # magnitude
# mag *= 255.0 / numpy.max(mag)  # normalize (Q&D)
# scipy.misc.imsave(dst_sobel, mag)

# get parameters
src_dataset = gdal.Open(src)
geotransform = src_dataset.GetGeoTransform()
spatialreference = src_dataset.GetProjection()
ncol = src_dataset.RasterXSize
コード例 #13
0
ndvi = stretch(ndvi)

# Create a blank 3-band image the same size as the ndvi
rgb = gd.numpy.zeros((3, len(ndvi), len(ndvi[0])), gd.numpy.uint8)

# Class list with ndvi upper range values.
# Note the lower and upper values are listed on the ends
classes = [58,73,110,147,184,220,255]

# Color look-up table (lut)
# The lut must match the number of classes
# Specified as R,G,B tuples from dark brown to dark green
lut = [[120,69,25], [255,178,74], [255,237,166], [173,232,94],
       [135,181,64], [3,156,0], [1,100,0]]

# Starting value of the first class
start = 1

# Process all classes.
for i in range(len(classes)):
    mask = gd.numpy.logical_and(\
    start <= ndvi, ndvi <= classes[i])
    for j in range(len(lut[i])):
        rgb[j] = gd.numpy.choose(mask, \
          (rgb[j], lut[i][j]))
    start = classes[i]+1    

# Save a geotiff image of the colorized ndvi.
gd.SaveArray(rgb, target, format="GTiff", prototype=source)

コード例 #14
0
# "Before" image
im1 = "before.tif"
# "After" image
im2 = "after.tif"
# Load before and after into arrays
ar1 = gdalnumeric.LoadFile(im1).astype(np.int8)
ar2 = gdalnumeric.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)
# Process all classes and assign colors
for i in range(len(classes)):
    mask = np.logical_and(start <= diff, diff <= classes[i])
    for j in range(len(lut[i])):
        rgb[j] = np.choose(mask, (rgb[j], lut[i][j]))
    start = classes[i] + 1
# Save the output image
gdalnumeric.SaveArray(rgb, "change.tif", format="GTiff", prototype=im2)
コード例 #15
0
geoTrans = srcImage.GetGeoTransform()

r = shapefile.Reader("../dati/%s.shp" % shp)
minX,minY,maxX,maxY = r.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]

geoTrans = list(geoTrans)
geoTrans[0] = minX
geoTrans[3] = minY

# Map points to pixels for drawing the county boundary # on a blank 8-bit, black and white, mask image.
pixels = []
for p in r.shape(0).points:
    pixels.append(world2Pixel(geoTrans,p[0],p[1]))
rasterPoly = Image.new("L",(pxWidth, pxHeight), 1)
# Create a blank image in PIL to draw the polygon.
rasterize = ImageDraw.Draw(rasterPoly)
rasterize.polygon( pixels, 0)
# Convert the PIL image to a NumPy array
mask = imageToArray( rasterPoly)
# Clip the image using the mask
clip = gdalnumeric.numpy.choose( mask, (clip, 0)). astype( gdalnumeric.numpy.uint8)
# Save ndvi as tiff
gdalnumeric.SaveArray(clip, output, format ="GTiff", prototype = raster)
コード例 #16
0
    pixels.append(world2Pixel(geoTrans, p[0], p[1]))

## Create a raster polygon image
rasterPoly = Image.new('L', (pxWidth, pxHeight), 1)
## Create a PIL drawing object
rasterize = ImageDraw.Draw(rasterPoly)
## Dump the pixels to the image
rasterize.polygon(pixels, 0)
## Hand the image back to gdal/gdalnumeric so we can use it as an array mask
mask = imageToArray(rasterPoly)

## Clip the red band using the mask
rClip = gdalnumeric.numpy.choose(mask,
                                 (rClip, 0)).astype(gdalnumeric.numpy.uint8)
## Clip the infrared band using the mask
irClip = gdalnumeric.numpy.choose(mask,
                                  (irClip, 0)).astype(gdalnumeric.numpy.uint8)

## We don't care about numpy warnings due to NaN values from clipping
gdalnumeric.numpy.seterr(all='ignore')

## NDVI equation: (infrared - red)/(infrared + red)
## *1.0 converts values to floats, +1.0 prevents ZeroDivisionErrors
ndvi = 1.0 * (irClip - rClip) / irClip + rClip + 1.0

## Remove any NaN values from the final product
ndvi = gdalnumeric.numpy.nan_to_num(ndvi)
## Save ndvi as tiff
gdalnumeric.SaveArray(ndvi, target, format='GTiff', prototype=source)
print target
コード例 #17
0
import os
import gdalnumeric

os.chdir('../dati/osgeopy-data/Washington/dem')
src = "tfc.tif"

arr = gdalnumeric.LoadFile(src)

gdalnumeric.SaveArray(arr[[0,1,2],:],"falco.tif",format="GTiff", prototype=src)
gdalnumeric.SaveArray(arr[[1,2,3],:],"talco.tif",format="GTiff", prototype=src)


コード例 #18
0
__author__ = 'Fabio'
import gdalnumeric

src = r"D:\workspace\geospatialAnalisys\dati\SatImage\SatImage.tif"
arr = gdalnumeric.LoadFile(src)

gdalnumeric.SaveArray(arr[[2,0,1],:],"../dati/SatImage/swap_201.tif",format="GTiff",prototype=src)
コード例 #19
0
from osgeo import gdal
import gdalnumeric
try:
    import numpy
except ImportError:
    import Numeric as numpy

class_defs = [(1, 10, 20), (2, 20, 30), (3, 128, 255)]

src_ds = gdal.Open('utm.tif')
xsize = src_ds.RasterXSize
ysize = src_ds.RasterYSize

src_image = gdalnumeric.LoadFile('utm.tif')

dst_image = numpy.zeros((ysize, xsize))

for class_info in class_defs:
    class_id = class_info[0]
    class_start = class_info[1]
    class_end = class_info[2]

    class_value = numpy.ones((ysize, xsize)) * class_id

    mask = numpy.bitwise_and(numpy.greater_equal(src_image, class_start),
                             numpy.less_equal(src_image, class_end))

    dst_image = numpy.choose(mask, (dst_image, class_value))

gdalnumeric.SaveArray(dst_image, 'classes.tif')
コード例 #20
0
def histogram(a, bins=list(range(0, 256))):
    fa = a.flat
    n = gdalnumeric.numpy.searchsorted(fa, bins)
    n = gdalnumeric.numpy.concatenate([n, [len(fa)]])
    hist = n[1:] - n[:-1]

    return (hist)


def stretch(a):
    hist = histogram(a)
    lut = []
    for b in range(0, len(hist), 256):
        step = reduce(operator.add, hist[b:b + 256]) / 255
        n = 0
        for i in range(256):
            lut.append(n / step)
            n += hist[i + b]

    gdalnumeric.numpy.take(lut, a, out=a)
    return (a)


src = './data/remote_sensing/swap.tif'
arr = gdalnumeric.LoadFile(src)
stretched = stretch(arr)
gdalnumeric.SaveArray(arr,
                      './data/remote_sensing/stretched.tif',
                      format='GTiff',
                      prototype=src)
コード例 #21
0
#  The above copyright notice and this permission notice shall be included
#  in all copies or substantial portions of the Software.
#
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
#  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
#  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
#  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
#  DEALINGS IN THE SOFTWARE.
#******************************************************************************

import gdal
import gdalnumeric
try:
    import numpy
except:
    import Numeric as numpy

src_ds = gdal.Open('complex.tif')
xsize = src_ds.RasterXSize
ysize = src_ds.RasterYSize

src_image = src_ds.GetRasterBand(1).ReadAsArray()
mag_image = pow(numpy.real(src_image)*numpy.real(src_image) \
                + numpy.imag(src_image)*numpy.imag(src_image),0.5)
gdalnumeric.SaveArray(mag_image, 'magnitude.tif')

phase_image = numpy.angle(src_image)
gdalnumeric.SaveArray(phase_image, 'phase.tif')
コード例 #22
0
# so we can use it as an array mask
mask = imageToArray(rasterPoly)
# Clip the red band using the mask
rClip = gdalnumeric.numpy.choose(mask, \
  (rClip, 0)).astype(gdalnumeric.numpy.uint8)
# Clip the infrared band using the mask
irClip = gdalnumeric.numpy.choose(mask, \
  (irClip, 0)).astype(gdalnumeric.numpy.uint8)

# We don't care about numpy warnings
# due to NaN values from clipping
gdalnumeric.numpy.seterr(all="ignore")

# NDVI equation: (infrared - red) / (infrared + red)
# *1.0 converts values to floats,
# +1.0 prevents ZeroDivisionErrors
ndvi = 1.0 * (irClip - rClip) / irClip + rClip + 1.0

# Remove any NaN values from the final product
ndvi = gdalnumeric.numpy.nan_to_num(ndvi)

# Save ndvi as tiff
gdalnumeric.SaveArray(ndvi, target, \
  format="GTiff", prototype=srcImage)

# Update georeferencing and NoData value
update = gdal.Open(target, 1)
update.SetGeoTransform(list(geoTrans))
update.GetRasterBand(1).SetNoDataValue(0.0)
update = None