Exemple #1
0
def do_recode(file, outfile, value_s, value_t, outTypeIn, format, options):
    fid0 = gdal.Open(file, GA_ReadOnly)
    ns = fid0.RasterXSize
    nl = fid0.RasterYSize
    nb = fid0.RasterCount

    if outTypeIn is None:
        outType = fid0.GetRasterBand(1).DataType
    else:
        outType = ParseType(outTypeIn)

    outDrv = gdal.GetDriverByName(format)
    outDs = outDrv.Create(outfile, ns, nl, nb, outType, options)
    outDs.SetProjection(fid0.GetProjection())
    outDs.SetGeoTransform(fid0.GetGeoTransform())

    for ib in range(nb):
        for il in range(nl):
            data0 = N.ravel(
                fid0.GetRasterBand(ib + 1).ReadAsArray(0, il, ns, 1))

            # set to N.zeros to enable auto cast whenever needed
            dataout = N.zeros(ns) + data0
            for it in range(len(value_s)):
                wtp = (data0 == value_s[it])
                if wtp.any():
                    dataout[wtp] = value_t[it]

            dataout.shape = (1, -1)
            outDs.GetRasterBand(ib + 1).WriteArray(N.array(dataout), 0, il)
            gdal.TermProgress((ib * (ns * nl) + il * ns) / float(ns * nl * nb))

    gdal.TermProgress(1)
Exemple #2
0
fpout.write(
    str(geotransform[0] + geotransform[1] / 2) + " " +
    str(geotransform[0] + geotransform[1] * (band.XSize - 0.5)) + "\n")
if geotransform[5] < 0:
    fpout.write(
        str(geotransform[3] + geotransform[5] * (band.YSize - 0.5)) + " " +
        str(geotransform[3] + geotransform[5] / 2) + "\n")
else:
    fpout.write(
        str(geotransform[3] + geotransform[5] / 2) + " " +
        str(geotransform[3] + geotransform[5] * (band.YSize - 0.5)) + "\n")
fpout.write(
    str(band.ComputeRasterMinMax(0)[0]) + " " +
    str(band.ComputeRasterMinMax(0)[1]) + "\n")

for i in range(band.YSize - 1, -1, -1):
    scanline = band.ReadAsArray(0, i, band.XSize, 1, band.XSize, 1)
    j = 0
    while j < band.XSize:
        fpout.write(str(scanline[0, j]))
        j = j + 1
        if j % 10:  # Print no more than 10 values per line
            fpout.write(" ")
        else:
            fpout.write("\n")
    fpout.write("\n")

    # Display progress report on terminal
    if not quiet:
        gdal.TermProgress(float(band.YSize - i) / band.YSize)
Exemple #3
0
if xsize is None:
    xsize = abs(geotransform[1])
if ysize is None:
    ysize = abs(geotransform[5])

inband = indataset.GetRasterBand(iBand)
if inband is None:
    print('Cannot load band', iBand, 'from the', infile)
    sys.exit(2)

numtype = gdalnumeric.GDALTypeCodeToNumericTypeCode(typ)
outline = Numeric.empty((1, inband.XSize), numtype)

prev = inband.ReadAsArray(0, 0, inband.XSize, 1, inband.XSize, 1)[0]
outband.WriteArray(outline, 0, 0)
gdal.TermProgress(0.0)

cur = inband.ReadAsArray(0, 1, inband.XSize, 1, inband.XSize, 1)[0]
outband.WriteArray(outline, 0, inband.YSize - 1)
gdal.TermProgress(1.0 / inband.YSize)

dx = 2 * xsize
dy = 2 * ysize

for i in range(1, inband.YSize - 1):
    next_ = inband.ReadAsArray(0, i + 1, inband.XSize, 1, inband.XSize, 1)[0]
    dzx = (cur[0:-2] - cur[2:]) * elstep
    dzy = (prev[1:-1] - next_[1:-1]) * elstep
    nx = -dy * dzx
    ny = dx * dzy
    nz = dx * dy
tif_ds = gtiff_driver.Create(tif_filename, src_ds.RasterXSize,
                             src_ds.RasterYSize, out_bands)

# ----------------------------------------------------------------------------
# We should copy projection information and so forth at this point.

tif_ds.SetProjection(src_ds.GetProjection())
tif_ds.SetGeoTransform(src_ds.GetGeoTransform())
if src_ds.GetGCPCount() > 0:
    tif_ds.SetGCPs(src_ds.GetGCPs(), src_ds.GetGCPProjection())

# ----------------------------------------------------------------------------
# Do the processing one scanline at a time.

gdal.TermProgress(0.0)
for iY in range(src_ds.RasterYSize):
    src_data = src_band.ReadAsArray(0, iY, src_ds.RasterXSize, 1)

    for iBand in range(out_bands):
        band_lookup = lookup[iBand]

        dst_data = Numeric.take(band_lookup, src_data)
        tif_ds.GetRasterBand(iBand + 1).WriteArray(dst_data, 0, iY)

    gdal.TermProgress((iY + 1.0) / src_ds.RasterYSize)

tif_ds = None

# ----------------------------------------------------------------------------
# Translate intermediate file to output format if desired format is not TIFF.
Exemple #5
0
def run(out_file=None, names=None, pre_init=[255]):

    global verbose, quiet
    verbose = 0
    quiet = 0
    format = 'GTiff'

    ulx = None
    psize_x = None
    separate = 0
    copy_pct = 0
    nodata = None
    create_options = []
    band_type = None
    createonly = 0

    gdal.AllRegister()

    if len(names) == 0:
        raise ValueError('No input files selected.')

    Driver = gdal.GetDriverByName(format)
    if Driver is None:
        raise ValueError(
            'Format driver %s not found, pick a supported driver.' % format)

    DriverMD = Driver.GetMetadata()
    if 'DCAP_CREATE' not in DriverMD:
        raise ValueError(
            'Format driver %s does not support creation and piecewise writing.\nPlease select a format that does, such as GTiff (the default) or HFA (Erdas Imagine).'
            % format)

    # Collect information on all the source files.
    file_infos = names_to_fileinfos(names)

    if ulx is None:
        ulx = file_infos[0].ulx
        uly = file_infos[0].uly
        lrx = file_infos[0].lrx
        lry = file_infos[0].lry

        for fi in file_infos:
            ulx = min(ulx, fi.ulx)
            uly = max(uly, fi.uly)
            lrx = max(lrx, fi.lrx)
            lry = min(lry, fi.lry)

    if psize_x is None:
        psize_x = file_infos[0].geotransform[1]
        psize_y = file_infos[0].geotransform[5]

    if band_type is None:
        band_type = file_infos[0].band_type

    # Try opening as an existing file.
    gdal.PushErrorHandler('CPLQuietErrorHandler')
    t_fh = gdal.Open(out_file, gdal.GA_Update)
    gdal.PopErrorHandler()

    # Create output file if it does not already exist.
    if t_fh is None:
        geotransform = [ulx, psize_x, 0, uly, 0, psize_y]

        xsize = int((lrx - ulx) / geotransform[1] + 0.5)
        ysize = int((lry - uly) / geotransform[5] + 0.5)

        if separate != 0:
            bands = len(file_infos)
        else:
            bands = file_infos[0].bands

        t_fh = Driver.Create(out_file, xsize, ysize, bands, band_type,
                             create_options)
        if t_fh is None:
            print('Creation failed, terminating gdal_merge.')
            sys.exit(1)

        t_fh.SetGeoTransform(geotransform)
        t_fh.SetProjection(file_infos[0].projection)

        if copy_pct:
            t_fh.GetRasterBand(1).SetRasterColorTable(file_infos[0].ct)
    else:
        if separate != 0:
            bands = len(file_infos)
            if t_fh.RasterCount < bands:
                print(
                    'Existing output file has less bands than the number of input files. You should delete it before. Terminating gdal_merge.'
                )
                sys.exit(1)
        else:
            bands = min(file_infos[0].bands, t_fh.RasterCount)

    # Do we need to pre-initialize the whole mosaic file to some value?
    if pre_init is not None:
        if t_fh.RasterCount <= len(pre_init):
            for i in range(t_fh.RasterCount):
                t_fh.GetRasterBand(i + 1).Fill(pre_init[i])
        elif len(pre_init) == 1:
            for i in range(t_fh.RasterCount):
                t_fh.GetRasterBand(i + 1).Fill(pre_init[0])

    # Copy data from source files into output file.
    t_band = 1

    if quiet == 0 and verbose == 0:
        gdal.TermProgress(0.0)
    fi_processed = 0

    for fi in file_infos:
        if createonly != 0:
            continue

        if verbose != 0:
            print("")
            print("Processing file %5d of %5d, %6.3f%% completed." \
                  % (fi_processed+1,len(file_infos),
                     fi_processed * 100.0 / len(file_infos)) )
            fi.report()

        if separate == 0:
            for band in range(1, bands + 1):
                fi.copy_into(t_fh, band, band, nodata)
        else:
            fi.copy_into(t_fh, 1, t_band, nodata)
            t_band = t_band + 1

        fi_processed = fi_processed + 1
        if quiet == 0 and verbose == 0:
            gdal.TermProgress(fi_processed / float(len(file_infos)))

    # Force file to be closed.
    t_fh = None
Exemple #6
0
                float(bv) ]
            c = [ \
                GT[0] + (i0 + i + 1) * GT[1] + (j0 + j) * GT[2],\
                GT[3] + (i0 + i + 1) * GT[4] + (j0 + j) * GT[5],\
                float(cv) ]
            if 1 == OSRds.IsGeographic():
                b[0], b[1] = pyproj.transform(P4ds, P4xy, b[0], b[1])
                c[0], c[1] = pyproj.transform(P4ds, P4xy, c[0], c[1])
            if nd != av:
                ## point a is valid
                a = [ \
                    GT[0] + (i0 + i) * GT[1] + (j0 + j) * GT[2],\
                    GT[3] + (i0 + i) * GT[4] + (j0 + j) * GT[5],\
                    float(av) ]
                if 1 == OSRds.IsGeographic():
                    a[0], a[1] = pyproj.transform(P4ds, P4xy, a[0], a[1])
                mesh.add_facet((a, b, c))
            if nd != dv:
                ## point d is valid
                d = [ \
                    GT[0] + (i0 + i + 1) * GT[1] + (j0 + j + 1) * GT[2],\
                    GT[3] + (i0 + i + 1) * GT[4] + (j0 + j + 1) * GT[5],\
                    float(dv) ]
                if 1 == OSRds.IsGeographic():
                    d[0], d[1] = pyproj.transform(P4ds, P4xy, d[0], d[1])
                mesh.add_facet((d, c, b))
        ## update progress each row
        gdal.TermProgress(float(j + 1) / nym1)

verbose("actual facet count: %s" % str(mesh.written))
Exemple #7
0
def main(argv=sys.argv):
    infile = None
    outfile = None
    iBand = 1
    quiet = 0

    # Parse command line arguments.
    i = 1
    while i < len(sys.argv):
        arg = sys.argv[i]

        if arg == '-b':
            i = i + 1
            iBand = int(sys.argv[i])

        elif arg == '-quiet':
            quiet = 1

        elif infile is None:
            infile = arg

        elif outfile is None:
            outfile = arg

        else:
            Usage()

        i = i + 1

    if infile is None:
        return Usage()
    if outfile is None:
        return Usage()

    indataset = gdal.Open(infile, gdal.GA_ReadOnly)
    if infile is None:
        print('Cannot open', infile)
        return 2
    geotransform = indataset.GetGeoTransform()
    band = indataset.GetRasterBand(iBand)
    if band is None:
        print('Cannot load band', iBand, 'from the', infile)
        return 2

    if not quiet:
        print('Size is ', indataset.RasterXSize, 'x', indataset.RasterYSize,
              'x', indataset.RasterCount)
        print('Projection is ', indataset.GetProjection())
        print('Origin = (', geotransform[0], ',', geotransform[3], ')')
        print('Pixel Size = (', geotransform[1], ',', geotransform[5], ')')
        print('Converting band number', iBand, 'with type',
              gdal.GetDataTypeName(band.DataType))

    # Header printing
    fpout = open(outfile, "wt")
    fpout.write("DSAA\n")
    fpout.write(str(band.XSize) + " " + str(band.YSize) + "\n")
    fpout.write(
        str(geotransform[0] + geotransform[1] / 2) + " " +
        str(geotransform[0] + geotransform[1] * (band.XSize - 0.5)) + "\n")
    if geotransform[5] < 0:
        fpout.write(
            str(geotransform[3] + geotransform[5] * (band.YSize - 0.5)) + " " +
            str(geotransform[3] + geotransform[5] / 2) + "\n")
    else:
        fpout.write(
            str(geotransform[3] + geotransform[5] / 2) + " " +
            str(geotransform[3] + geotransform[5] * (band.YSize - 0.5)) + "\n")
    fpout.write(
        str(band.ComputeRasterMinMax(0)[0]) + " " +
        str(band.ComputeRasterMinMax(0)[1]) + "\n")

    for i in range(band.YSize - 1, -1, -1):
        scanline = band.ReadAsArray(0, i, band.XSize, 1, band.XSize, 1)
        j = 0
        while j < band.XSize:
            fpout.write(str(scanline[0, j]))
            j = j + 1
            if j % 10:  # Print no more than 10 values per line
                fpout.write(" ")
            else:
                fpout.write("\n")
        fpout.write("\n")

        # Display progress report on terminal
        if not quiet:
            gdal.TermProgress(float(band.YSize - i) / band.YSize)
    return 0
def hsv_merge(work_root, rgb, gray, dst):
    src_rgb_filename = os.path.join(work_root, rgb)
    src_greyscale_filename = os.path.join(work_root, gray)
    dst_rgb_filename = os.path.join(work_root, dst)
    if os.path.exists(dst_rgb_filename):
        return
    hilldataset = gdal.Open(src_greyscale_filename, GA_ReadOnly)
    colordataset = gdal.Open(src_rgb_filename, GA_ReadOnly)

    #check for 3 bands in the color file
    if (colordataset.RasterCount != 3):
        print 'Source image does not appear to have three bands as required.'
        sys.exit(1)

    #define output format, name, size, type and set projection
    out_driver = gdal.GetDriverByName(format)
    outdataset = out_driver.Create(dst_rgb_filename, colordataset.RasterXSize, \
        colordataset.RasterYSize, colordataset.RasterCount, type)
    outdataset.SetProjection(hilldataset.GetProjection())
    outdataset.SetGeoTransform(hilldataset.GetGeoTransform())

    #assign RGB and hillshade bands
    rBand = colordataset.GetRasterBand(1)
    gBand = colordataset.GetRasterBand(2)
    bBand = colordataset.GetRasterBand(3)
    hillband = hilldataset.GetRasterBand(1)

    #check for same file size
    if ((rBand.YSize != hillband.YSize) or (rBand.XSize != hillband.XSize)):
        print 'Color and hilshade must be the same size in pixels.'
        sys.exit(1)

    #set progress bar to 0
    #gdal.TermProgress( 0.0 )

    #loop over lines to apply hillshade
    for i in range(hillband.YSize - 1, -1, -1):
        #load RGB and Hillshade arrays
        rScanline = rBand.ReadAsArray(0, i, hillband.XSize, 1, hillband.XSize,
                                      1)
        gScanline = gBand.ReadAsArray(0, i, hillband.XSize, 1, hillband.XSize,
                                      1)
        bScanline = bBand.ReadAsArray(0, i, hillband.XSize, 1, hillband.XSize,
                                      1)
        hillScanline = hillband.ReadAsArray(0, i, hillband.XSize, 1,
                                            hillband.XSize, 1)

        #convert to HSV
        hsv = rgb_to_hsv(rScanline, gScanline, bScanline)

        #replace v with hillshade
        hsv_adjusted = numpy.asarray([hsv[0], hsv[1], hillScanline])

        #convert back to RGB
        dst_rgb = hsv_to_rgb(hsv_adjusted)

        #write out new RGB bands to output one band at a time
        outband = outdataset.GetRasterBand(1)
        outband.WriteArray(dst_rgb[0], 0, i)
        outband = outdataset.GetRasterBand(2)
        outband.WriteArray(dst_rgb[1], 0, i)
        outband = outdataset.GetRasterBand(3)
        outband.WriteArray(dst_rgb[2], 0, i)

        #update progress line
        gdal.TermProgress(1.0 - (float(i) / hillband.YSize))
def Main():
    # Say who we are and what we do
    print(
        "This Python scruipt creates a histogram from a GIS input file using GDAL and Matplotlib"
    )

    # Do some initialization
    indemfile = None
    outfile = None

    # Parse command line arguments
    i = 1
    while i < len(sys.argv):
        arg = sys.argv[i]

        if i == 1:
            indemfile = arg
        elif i == 2:
            outfile = arg
        i += 1

    # Do some initialization
    nbins = 100
    grid = True
    xlabel = "Elevation"
    ylabel = 'Frequency'
    verbose = True

    # Do we have both filenames?
    if indemfile is None or outfile is None:
        Usage()

    # OK, open the input DEM file using GDAL
    indata = gdal.Open(indemfile)
    if indemfile == None:
        # Error, give up
        print("Cannot open", indemfile)
        sys.exit(2)

    # Now read in some information using GDAL
    geotransform = indata.GetGeoTransform()
    nBand = 1  # Assume that there is only one band of data
    band = indata.GetRasterBand(nBand)
    if band == None:
        # Error, give up
        print("Cannot load band", nBand, "from", indemfile)
        sys.exit(2)

    if verbose:
        # Display some information about the DEM
        print("Reading from", indemfile)
        print("   Size is", indata.RasterXSize, "x", indata.RasterYSize, "x",
              indata.RasterCount)
        print("   Projection is", indata.GetProjection())
        print("   Origin = (", geotransform[0], ",", geotransform[3], ")")
        print("   Pixel size = (", geotransform[1], ",", geotransform[5], ")")
        print("   Overall size =", indata.RasterXSize * geotransform[1], ",",
              indata.RasterYSize * geotransform[5])
        datatype = gdal.GetDataTypeName(band.DataType)
        print("   Reading band number", nBand, "with type", datatype)

        min = band.GetMinimum()
        max = band.GetMaximum()
        if min is None or max is None:
            (min, max) = band.ComputeRasterMinMax(nBand)
        print("   Min = %.3f, Max = %.3f" % (min, max))

        if band.GetOverviewCount() > 0:
            print("   Band has", band.GetOverviewCount(), "overviews")

        if not band.GetRasterColorTable() is None:
            print("   Band has a color table with",
                  band.GetRasterColorTable().GetCount(), "entries")

        print("Storing data from", indemfile)

    # Now create a 1D array to store the data
    data_list = [0] * (indata.RasterXSize * indata.RasterYSize)

    # And read the data into the array
    n = 0
    for i in range(band.YSize - 1, -1, -1):
        scanline = band.ReadAsArray(0, i, band.XSize, 1, band.XSize, 1)
        j = 0
        while j < band.XSize:
            data_list[n] = scanline[0, j]
            j += 1
            n += 1

            if verbose:
                gdal.TermProgress(float(band.YSize - i) / band.YSize)

    n, bins, patches = plt.hist(data_list,
                                nbins,
                                normed=False,
                                cumulative=False,
                                histtype='bar',
                                log=False,
                                facecolor='green',
                                alpha=0.75)
    plt.xlabel(xlabel)  # label the x axis
    plt.ylabel(ylabel)  # label the y axis
    plt.grid(grid)  # put a grid on it
    plt.show()  # plot the graph

    # Open the output file TODO check that this opens correctly at runtime
    fp_out = open(outfile, "w")
    for i in range(len(data_list)):
        fp_out.write("%7.6f" % data_list[i])
        fp_out.write("\n")

    fp_out.close()

    if verbose:
        print("DEM graphed, end of run")
    def readGdalFile(self, bandDim_, bandNumber_, dataType_):
        """
        Reads a GDAL file and returns data as numpy array

        A GDAL dataset contains a list of raster bands all having the same area
        and resolution. Furthermore the dataset contains metadata, a georeferencing
        transform as well as a coordinate system, the size of the raster and other 
        information.

        INPUT_PARAMETERS:
        bandDim         - Define which NetCDF dimension should be represented by GDAL bands (string)
        bandNumber      - Output image file will contain input band numbers from 1 to 'bandNumber';
            if bandNumber is 'None', all bands will be reprojected (integer)
        dataType        - Define output data type of numpy array (string)

        RETURN_VALUE:
        numpy data array with data from GDAL input dataset
        """
        
        #Get GDAL input dataset and define settings
        #-------------------------------------------------------------------------------
        
        #Set data type for output numpy array
        firstBand = self.pDataset.GetRasterBand(1)
        if not dataType_ == '': #if Parser.dataType is set or if default NUMPY_DATATYPE != '' then use this value
            pDataType = self.pProcessingTool.dataType_2Numpy(dataType_) #Convert to numpy dtype
        elif not gdal.GetDataTypeName(firstBand.DataType) is None: #use Dataset type value if there is a type available
            pDataType = self.pProcessingTool.dataType_2Numpy(gdal.GetDataTypeName(firstBand.DataType)) #Convert to numpy dtype
        else:
            raise Exception("Error: No valid data type can be set. Input value is: '" + str(dataType_) + "'")

        #Define what bands should be used (from 1 to bandNumber, or all bands if bandNumber is None)
        bands = self.__getBandNumber(bandNumber_)

        #Define what numpy (NetCDF) dimension should correspond to input bands (self.pDataset.RasterCount)
        dimY = int(self.pDataset.RasterYSize) #Last but one axis top to bottom: lat -> row
        dimX = int(self.pDataset.RasterXSize)  #Last axis left to right: lon -> col
       
        if bandDim_ == 'var':
            pDocGradsNumpy = numpy.zeros([int(bands), int(1), int(1), dimY, dimX], dtype = pDataType)
        elif bandDim_ == 'time':
            pDocGradsNumpy = numpy.zeros([int(1), int(bands), int(1), dimY, dimX], dtype = pDataType)
        elif bandDim_ ==  'height':
            pDocGradsNumpy = numpy.zeros([int(1), int(1), int(bands), dimY, dimX], dtype = pDataType)
        else:
            raise Exception("Error: Value of bandDim argument not allowed. Valid values are 'var', 'time' or 'height'" )
               

        #Read input dataset and save it to numpy file
        #-------------------------------------------------------------------------------
        #Easiest and best technique for data reading is line per line. Better would be block size reading.
        #Reading one pixel at a time is inefficient. Reading the entire image at once is most efficient, but can cause
        #problems if RAM is not sufficient.

        for cnBand in range(1, bands + 1, 1): #For all bands defined
            pInBand = self.pDataset.GetRasterBand(cnBand) #GetRasterBand is 1-based index

            for cnRow in range(pInBand.YSize -1, -1, -1): #Each row in file, Y origin is on upper left in GDAL!

                #DimRowCount must run in inverse order as cnRow (from lower left to upper left) because of Y origin
                dimRowCn = pInBand.YSize - 1 - cnRow

                #scanline = pInBand.ReadAsArray(0, cnRow, pInBand.XSize, 1, \
                #                    pInBand.XSize, 1, GDT_Float32 )
                #data = GdalRasterBand.ReadRaster(int nXOffset, int nYOffset, int nXSize, int nYSize, \
                    #int nBuffXSize, int nBuffYSize, GdalDataType eBufType, int nPixelSpace, int nLineSpace)
                scanline = pInBand.ReadRaster( 0, cnRow, pInBand.XSize, 1, \
                                     pInBand.XSize, 1, GDT_Float32 )

                #Convert data and cast to numpy data array

                #To unpack use IEEE 754 binary32 (for 'f') or binary 64 (for 'd') format
                scanline_tupleOfFloats = struct.unpack('f' * pInBand.XSize, scanline)# convert data to Python values

                scanline_numpy = numpy.asarray(scanline_tupleOfFloats)

                if bandDim_ == 'var':
                    pDocGradsNumpy[cnBand-1,0,0,dimRowCn,:] = scanline_numpy.astype(pDataType) #cnBand - 1 because of 1-based index
                elif bandDim_ == 'time':
                    pDocGradsNumpy[0,cnBand-1,0,dimRowCn,:] = scanline_numpy.astype(pDataType) #cnBand - 1 because of 1-based index
                elif bandDim_ ==  'height':
                    pDocGradsNumpy[0,0,cnBand-1,dimRowCn,:] = scanline_numpy.astype(pDataType) #cnBand - 1 because of 1-based index
                else:
                    raise Exception("Error: Value of bandDim argument ('" + str(bandDim_) + "') not allowed. Valid values are 'var', 'time' or 'height'")

                #gdal.TermProgress(float(pInBand.YSize-cnRow) / pInBand.YSize)
              
            gdal.TermProgress(1-(float(self.pDataset.RasterCount - cnBand) / self.pDataset.RasterCount))

        return pDocGradsNumpy
            # Points b and c are required for both facets, so if either
            # are unavailable, we can skip this pixel altogether.
            if skip(bv) or skip(cv):
                continue

            b = (t[0] + ((xmin + x) * t[1]) + ((ymin + y + 1) * t[2]),
                 t[3] + ((xmin + x) * t[4]) + ((ymin + y + 1) * t[5]),
                 (zscale * (float(bv) - zmin)) + args.base)

            c = (t[0] + ((xmin + x + 1) * t[1]) + ((ymin + y) * t[2]),
                 t[3] + ((xmin + x + 1) * t[4]) + ((ymin + y) * t[5]),
                 (zscale * (float(cv) - zmin)) + args.base)

            if not skip(av):
                a = (t[0] + ((xmin + x) * t[1]) + ((ymin + y) * t[2]),
                     t[3] + ((xmin + x) * t[4]) + ((ymin + y) * t[5]),
                     (zscale * (float(av) - zmin)) + args.base)
                mesh.add_facet((a, b, c))

            if not skip(dv):
                d = (t[0] + ((xmin + x + 1) * t[1]) + ((ymin + y + 1) * t[2]),
                     t[3] + ((xmin + x + 1) * t[4]) + ((ymin + y + 1) * t[5]),
                     (zscale * (float(dv) - zmin)) + args.base)
                mesh.add_facet((d, c, b))

        # Update progress each row
        gdal.TermProgress(float(y + 1) / mh)

log("actual facet count: %s" % str(mesh.written))
Exemple #12
0
        goreStart = 0
        goreCenter = goreWidth / 2

        # iterate over each gore as specified by the user
        # based on C# implementation by winski software
        for i in range(gores):

            # iterate over each pixel in output gore
            for x in range(goreWidth):
                dn = inline[0, goreStart + x]
                # set new position for pixel value in output array
                # updated with round to increase overlap at gore edge
                newX = int(round(goreCenter + math.cos((-math.pi/2.0) + (math.pi * float(y) / float(iBand.YSize))) \
                           * (x - (goreWidth / 2.0))))
                dstline[newX] = dn

            # move start and center to the correct places
            goreStart = goreStart + goreWidth
            goreCenter = goreCenter + goreWidth

        #write out scanline for the current band
        out_array = np.asarray([dstline])
        outband.WriteArray(out_array, 0, y)

        #update progress line
        if not quiet:
            gdal.TermProgress(1.0 - (float(y) / iBand.YSize))

#set output to None to close file
outdataset = None
Exemple #13
0
#gdal.TermProgress( 0.0 )

#loop over lines to apply hillshade
for i in range(hillband.YSize - 1, -1, -1):
    #load RGB and Hillshade arrays
    rScanline = rBand.ReadAsArray(0, i, hillband.XSize, 1, hillband.XSize, 1)
    gScanline = gBand.ReadAsArray(0, i, hillband.XSize, 1, hillband.XSize, 1)
    bScanline = bBand.ReadAsArray(0, i, hillband.XSize, 1, hillband.XSize, 1)
    hillScanline = hillband.ReadAsArray(0, i, hillband.XSize, 1,
                                        hillband.XSize, 1)

    #convert to HSV
    hsv = rgb_to_hsv(rScanline, gScanline, bScanline)

    #replace v with hillshade
    hsv_adjusted = numpy.asarray([hsv[0], hsv[1], hillScanline])

    #convert back to RGB
    dst_rgb = hsv_to_rgb(hsv_adjusted)

    #write out new RGB bands to output one band at a time
    outband = outdataset.GetRasterBand(1)
    outband.WriteArray(dst_rgb[0], 0, i)
    outband = outdataset.GetRasterBand(2)
    outband.WriteArray(dst_rgb[1], 0, i)
    outband = outdataset.GetRasterBand(3)
    outband.WriteArray(dst_rgb[2], 0, i)

    #update progress line
    gdal.TermProgress(1.0 - (float(i) / hillband.YSize))
Exemple #14
0
def main(argv=sys.argv):
    infile = None
    outfile = None
    iBand = 1  # The first band will be converted by default
    driver_name = 'GTiff'
    typ = gdal.GDT_Byte

    lsrcaz = None
    lsrcel = None
    elstep = 1.0
    xsize = None
    ysize = None
    dyn_range = 255.0

    # Parse command line arguments.
    i = 1
    while i < len(argv):
        arg = argv[i]

        if arg == '-b':
            i += 1
            iBand = int(argv[i])

        elif arg == '-ot':
            i += 1
            typ = ParseType(argv[i])

        elif arg == '-lsrcaz':
            i += 1
            lsrcaz = float(argv[i])

        elif arg == '-lsrcel':
            i += 1
            lsrcel = float(argv[i])

        elif arg == '-elstep':
            i += 1
            elstep = float(argv[i])

        elif arg == '-dx':
            i += 1
            xsize = float(argv[i])

        elif arg == '-dy':
            i += 1
            ysize = float(argv[i])

        elif arg == '-r':
            i += 1
            dyn_range = float(argv[i])

        elif infile is None:
            infile = arg

        elif outfile is None:
            outfile = arg

        else:
            return Usage()

        i += 1

    if infile is None:
        return Usage()
    if outfile is None:
        return Usage()
    if lsrcaz is None:
        return Usage()
    if lsrcel is None:
        return Usage()

    # translate angles from degrees to radians
    lsrcaz = lsrcaz / 180.0 * math.pi
    lsrcel = lsrcel / 180.0 * math.pi

    lx = -math.sin(lsrcaz) * math.cos(lsrcel)
    ly = math.cos(lsrcaz) * math.cos(lsrcel)
    lz = math.sin(lsrcel)
    lxyz = math.sqrt(lx**2 + ly**2 + lz**2)

    indataset = gdal.Open(infile, gdal.GA_ReadOnly)
    if indataset is None:
        print('Cannot open', infile)
        return 2

    if indataset.RasterXSize < 3 or indataset.RasterYSize < 3:
        print('Input image is too small to process, minimum size is 3x3')
        return 3

    out_driver = gdal.GetDriverByName(driver_name)
    outdataset = out_driver.Create(outfile, indataset.RasterXSize,
                                   indataset.RasterYSize,
                                   indataset.RasterCount, typ)
    outband = outdataset.GetRasterBand(1)

    geotransform = indataset.GetGeoTransform()
    projection = indataset.GetProjection()

    if xsize is None:
        xsize = abs(geotransform[1])
    if ysize is None:
        ysize = abs(geotransform[5])

    inband = indataset.GetRasterBand(iBand)
    if inband is None:
        print('Cannot load band', iBand, 'from the', infile)
        return 2

    numtype = gdal_array.GDALTypeCodeTonpTypeCode(typ)
    outline = np.empty((1, inband.XSize), numtype)

    prev = inband.ReadAsArray(0, 0, inband.XSize, 1, inband.XSize, 1)[0]
    outband.WriteArray(outline, 0, 0)
    gdal.TermProgress(0.0)

    cur = inband.ReadAsArray(0, 1, inband.XSize, 1, inband.XSize, 1)[0]
    outband.WriteArray(outline, 0, inband.YSize - 1)
    gdal.TermProgress(1.0 / inband.YSize)

    dx = 2 * xsize
    dy = 2 * ysize

    for i in range(1, inband.YSize - 1):
        next_ = inband.ReadAsArray(0, i + 1, inband.XSize, 1, inband.XSize,
                                   1)[0]
        dzx = (cur[0:-2] - cur[2:]) * elstep
        dzy = (prev[1:-1] - next_[1:-1]) * elstep
        nx = -dy * dzx
        ny = dx * dzy
        nz = dx * dy
        nxyz = nx * nx + ny * ny + nz * nz
        nlxyz = nx * lx + ny * ly + nz * lz
        cosine = dyn_range * (nlxyz / (lxyz * np.sqrt(nxyz)))
        cosine = np.clip(cosine, 0.0, dyn_range)
        outline[0, 1:-1] = cosine.astype(numtype)
        outband.WriteArray(outline, 0, i)

        prev = cur
        cur = next_

        # Display progress report on terminal
        gdal.TermProgress(float(i + 1) / (inband.YSize - 1))

    outdataset.SetGeoTransform(geotransform)
    outdataset.SetProjection(projection)

    return 0
Exemple #15
0
def main(argv=None):

    global verbose, quiet
    verbose = 0
    quiet = 0
    names = []
    format = 'GTiff'
    out_file = 'out.tif'

    ulx = None
    psize_x = None
    separate = 0
    copy_pct = 0
    nodata = None
    create_options = []
    pre_init = []
    band_type = None
    createonly = 0

    gdal.AllRegister()
    if argv is None:
        argv = sys.argv
    argv = gdal.GeneralCmdLineProcessor(argv)
    if argv is None:
        sys.exit(0)

    # Parse command line arguments.
    i = 1
    while i < len(argv):
        arg = argv[i]

        if arg == '-o':
            i = i + 1
            out_file = argv[i]

        elif arg == '-v':
            verbose = 1

        elif arg == '-q' or arg == '-quiet':
            quiet = 1

        elif arg == '-createonly':
            createonly = 1

        elif arg == '-separate':
            separate = 1

        elif arg == '-seperate':
            separate = 1

        elif arg == '-pct':
            copy_pct = 1

        elif arg == '-ot':
            i = i + 1
            band_type = gdal.GetDataTypeByName(argv[i])
            if band_type == gdal.GDT_Unknown:
                print('Unknown GDAL data type: ', argv[i])
                sys.exit(1)

        elif arg == '-init':
            i = i + 1
            str_pre_init = argv[i].split()
            for x in str_pre_init:
                pre_init.append(float(x))

        elif arg == '-n':
            i = i + 1
            nodata = float(argv[i])

        elif arg == '-f':
            # for backward compatibility.
            i = i + 1
            format = argv[i]

        elif arg == '-of':
            i = i + 1
            format = argv[i]

        elif arg == '-co':
            i = i + 1
            create_options.append(argv[i])

        elif arg == '-ps':
            psize_x = float(argv[i + 1])
            psize_y = -1 * abs(float(argv[i + 2]))
            i = i + 2

        elif arg == '-ul_lr':
            ulx = float(argv[i + 1])
            uly = float(argv[i + 2])
            lrx = float(argv[i + 3])
            lry = float(argv[i + 4])
            i = i + 4

        elif arg[:1] == '-':
            print('Unrecognised command option: ', arg)
            Usage()
            sys.exit(1)

        else:
            # Expand any possible wildcards from command line arguments
            f = glob.glob(arg)
            if len(f) == 0:
                print('File not found: "%s"' % (str(arg)))
            names += f  # append 1 or more files
        i = i + 1

    if len(names) == 0:
        print('No input files selected.')
        Usage()
        sys.exit(1)

    Driver = gdal.GetDriverByName(format)
    if Driver is None:
        print('Format driver %s not found, pick a supported driver.' % format)
        sys.exit(1)

    DriverMD = Driver.GetMetadata()
    if 'DCAP_CREATE' not in DriverMD:
        print(
            'Format driver %s does not support creation and piecewise writing.\nPlease select a format that does, such as GTiff (the default) or HFA (Erdas Imagine).'
            % format)
        sys.exit(1)

    # Collect information on all the source files.
    file_infos = names_to_fileinfos(names)

    if ulx is None:
        ulx = file_infos[0].ulx
        uly = file_infos[0].uly
        lrx = file_infos[0].lrx
        lry = file_infos[0].lry

        for fi in file_infos:
            ulx = min(ulx, fi.ulx)
            uly = max(uly, fi.uly)
            lrx = max(lrx, fi.lrx)
            lry = min(lry, fi.lry)

    if psize_x is None:
        psize_x = file_infos[0].geotransform[1]
        psize_y = file_infos[0].geotransform[5]

    if band_type is None:
        band_type = file_infos[0].band_type

    # Try opening as an existing file.
    gdal.PushErrorHandler('CPLQuietErrorHandler')
    t_fh = gdal.Open(out_file, gdal.GA_Update)
    gdal.PopErrorHandler()

    # Create output file if it does not already exist.
    if t_fh is None:
        geotransform = [ulx, psize_x, 0, uly, 0, psize_y]

        xsize = int((lrx - ulx) / geotransform[1] + 0.5)
        ysize = int((lry - uly) / geotransform[5] + 0.5)

        if separate != 0:
            bands = len(file_infos)
        else:
            bands = file_infos[0].bands

        t_fh = Driver.Create(out_file, xsize, ysize, bands, band_type,
                             create_options)
        if t_fh is None:
            print('Creation failed, terminating gdal_merge.')
            sys.exit(1)

        t_fh.SetGeoTransform(geotransform)
        t_fh.SetProjection(file_infos[0].projection)

        if copy_pct:
            t_fh.GetRasterBand(1).SetRasterColorTable(file_infos[0].ct)
    else:
        if separate != 0:
            bands = len(file_infos)
            if t_fh.RasterCount < bands:
                print(
                    'Existing output file has less bands than the number of input files. You should delete it before. Terminating gdal_merge.'
                )
                sys.exit(1)
        else:
            bands = min(file_infos[0].bands, t_fh.RasterCount)

    # Do we need to pre-initialize the whole mosaic file to some value?
    if pre_init is not None:
        if t_fh.RasterCount <= len(pre_init):
            for i in range(t_fh.RasterCount):
                t_fh.GetRasterBand(i + 1).Fill(pre_init[i])
        elif len(pre_init) == 1:
            for i in range(t_fh.RasterCount):
                t_fh.GetRasterBand(i + 1).Fill(pre_init[0])

    # Copy data from source files into output file.
    t_band = 1

    if quiet == 0 and verbose == 0:
        gdal.TermProgress(0.0)
    fi_processed = 0

    for fi in file_infos:
        if createonly != 0:
            continue

        if verbose != 0:
            print("")
            print("Processing file %5d of %5d, %6.3f%% completed." \
                  % (fi_processed+1,len(file_infos),
                     fi_processed * 100.0 / len(file_infos)) )
            fi.report()

        if separate == 0:
            for band in range(1, bands + 1):
                fi.copy_into(t_fh, band, band, nodata)
        else:
            fi.copy_into(t_fh, 1, t_band, nodata)
            t_band = t_band + 1

        fi_processed = fi_processed + 1
        if quiet == 0 and verbose == 0:
            gdal.TermProgress(fi_processed / float(len(file_infos)))

    # Force file to be closed.
    t_fh = None
Exemple #16
0
def main(argv):
    frmt = 'GTiff'
    src_filename = None
    dst_filename = None
    src_band_n = 1
    dst_band_n = 1
    lut_filename = None
    create_options = []

    gdal.AllRegister()
    argv = gdal.GeneralCmdLineProcessor(argv)
    if argv is None:
        return 0

    # Parse command line arguments.
    i = 1
    while i < len(argv):
        arg = argv[i]

        if arg == '-of':
            i = i + 1
            frmt = argv[i]

        elif arg == '-co':
            i = i + 1
            create_options.append(argv[i])

        elif arg == '-lutfile':
            i = i + 1
            lut_filename = argv[i]

        elif arg == '-srcband':
            i = i + 1
            src_band_n = int(argv[i])

        elif arg == '-dstband':
            i = i + 1
            dst_band_n = int(argv[i])

        elif src_filename is None:
            src_filename = argv[i]

        elif dst_filename is None:
            dst_filename = argv[i]

        else:
            Usage()

        i = i + 1

    if src_filename is None or lut_filename is None:
        Usage()

    # ----------------------------------------------------------------------------
    # Load the LUT file.

    lut = read_lut(lut_filename)

    max_val = 0
    for entry in lut:
        if entry > max_val:
            max_val = entry

    if max_val > 255:
        tc = numpy.uint16
        gc = gdal.GDT_UInt16
    else:
        tc = numpy.uint8
        gc = gdal.GDT_Byte

    # ----------------------------------------------------------------------------
    # Convert the LUT from a normal array to a numpy style array.

    if len(lut) <= 256:
        lookup = numpy.arange(256)
        for i in range(min(256, len(lut))):
            lookup[i] = lut[i]
    else:
        lookup = numpy.arange(65536)
        for i in range(min(65536, len(lut))):
            lookup[i] = lut[i]

    lookup = lookup.astype(tc)

    # ----------------------------------------------------------------------------
    # Open source file

    if dst_filename is None:
        src_ds = gdal.Open(src_filename, gdal.GA_Update)
        dst_ds = src_ds
    else:
        src_ds = gdal.Open(src_filename)
        dst_ds = None

    if src_ds is None:
        print('Unable to open ', src_filename)
        return 1

    src_band = src_ds.GetRasterBand(src_band_n)

    # ----------------------------------------------------------------------------
    # Open or create output file.

    dst_driver = gdal.GetDriverByName(frmt)
    if dst_driver is None:
        print('"%s" driver not registered.' % frmt)
        return 1

    if dst_ds is None:
        try:
            dst_ds = gdal.Open(dst_filename, gdal.GA_Update)
        except:
            dst_ds = None

        if dst_ds is None:
            dst_ds = dst_driver.Create(dst_filename,
                                       src_ds.RasterXSize,
                                       src_ds.RasterYSize,
                                       1, gc, options=create_options)
            dst_ds.SetProjection(src_ds.GetProjection())
            dst_ds.SetGeoTransform(src_ds.GetGeoTransform())


    dst_band = dst_ds.GetRasterBand(dst_band_n)

    # ----------------------------------------------------------------------------
    # Do the processing one scanline at a time.

    gdal.TermProgress(0.0)
    for iY in range(src_ds.RasterYSize):
        src_data = src_band.ReadAsArray(0, iY, src_ds.RasterXSize, 1)

        dst_data = numpy.take(lookup, src_data)
        dst_band.WriteArray(dst_data, 0, iY)

        gdal.TermProgress((iY + 1.0) / src_ds.RasterYSize)

    src_ds = None
    dst_ds = None

    return 0
Exemple #17
0
red_band = red_dataset.GetRasterBand(1)
if (green_dataset.RasterCount > 1):
    green_band = green_dataset.GetRasterBand(2)
else:
    green_band = green_dataset.GetRasterBand(1)
if (blue_dataset.RasterCount > 2):
    blue_band = blue_dataset.GetRasterBand(3)
else:
    blue_band = blue_dataset.GetRasterBand(1)

red_outband = outdataset.GetRasterBand(1)
green_outband = outdataset.GetRasterBand(2)
blue_outband = outdataset.GetRasterBand(3)

gdal.TermProgress(0.0)

for i in range(red_band.YSize - 1, -1, -1):
    red_scanline = red_band.ReadAsArray(0, i, red_band.XSize, 1,
                                        red_band.XSize, 1).astype(float)
    green_scanline = green_band.ReadAsArray(0, i, green_band.XSize, 1,
                                            green_band.XSize, 1).astype(float)
    blue_scanline = blue_band.ReadAsArray(0, i, blue_band.XSize, 1,
                                          blue_band.XSize, 1).astype(float)

    red_scanline = numpy.power(red_scanline * scale / 65535.0,
                               1.0 / gamma) * 255.0
    green_scanline = numpy.power(green_scanline * scale / 65535.0,
                                 1.0 / gamma) * 255.0
    blue_scanline = numpy.power(blue_scanline * scale / 65535.0,
                                1.0 / gamma) * 255.0