예제 #1
0
    def multiply_bands(self, s1, s2, a, b, c):
        """Method <multiply_bands> computes the production of the bands
	   Arguments:
		s1 - first source band;
		s2 - second source band;
		a,b,c - unusable;
	   The output raster pixel density is calculated by formula
	        res =  X * Y
	   where  X and Y are densities of first and second source bands.
	"""
        for i in range(s1.YSize):
            s1_buf = gdalnumeric.BandReadAsArray(s1, 0, i, s1.XSize, 1)[0]
            s2_buf = gdalnumeric.BandReadAsArray(s2, 0, i, s1.XSize, 1)[0]
            temp_buf = 1. * s1_buf * s2_buf
            self.out_buf[i, 0:] = \
         clip_result(self.numtype, temp_buf).astype(self.numtype)
예제 #2
0
    def add_bands(self, s1, s2, a, b, c):
        """<add_bands> method computes the linear combination of the bands
	   Arguments:
		s1 - first source band;
		s2 - second source band;
		a,b,c - linear combination coefficients;
	   The output raster pixel density is calculated by formula
	        res = a * X + b * Y + c
	   where  X and Y are densities of first and second source bands
	"""
        for i in range(s1.YSize):
            s1_buf = gdalnumeric.BandReadAsArray(s1, 0, i, s1.XSize, 1)[0]
            s2_buf = gdalnumeric.BandReadAsArray(s2, 0, i, s1.XSize, 1)[0]
            temp_buf = a * s1_buf + b * s2_buf + c
            self.out_buf[i, 0:] = \
         clip_result(self.numtype, temp_buf).astype(self.numtype)
예제 #3
0
    def veg_index(self, s1, s2, a, b, c):
        """Method <veg_index> computes the vegetation index for pair of the bands
	   Arguments:
		s1 - first source band;
		s2 - second source band;
		a,b - coefficients;
		c - unusable;
	   The output raster pixel density is calculated by formula
	        res = a * (X - Y) / (X + Y) + b
	   where  X and Y are densities of first and second source bands.
	"""
        for i in range(s1.YSize):
            s1_buf = gdalnumeric.BandReadAsArray(s1, 0, i, s1.XSize, 1)[0]
            s2_buf = gdalnumeric.BandReadAsArray(s2, 0, i, s1.XSize, 1)[0]
            temp_buf1 = s1_buf + s2_buf + 1
            temp_buf = a * (s1_buf - s2_buf) / temp_buf1 + b
            self.out_buf[i, 0:] = \
         clip_result(self.numtype, temp_buf).astype(self.numtype)
예제 #4
0
    def divide_bands(self, s1, s2, a, b, c):
        """<divide_bands> method executes the division of the bands
	   Arguments:
		s1 - first source band;
		s2 - second source band;
		a,b,c - coefficients;
	   The output raster pixel density is calculated by formula
	        res = a * X / (b + Y) + c
	   where  X and Y are densities of first and second source bands
	"""
        for i in range(s1.YSize):
            s1_buf = gdalnumeric.BandReadAsArray(s1, 0, i, s1.XSize, 1)[0]
            s2_buf = gdalnumeric.BandReadAsArray(s2, 0, i, s1.XSize, 1)[0]
            try:
                temp_buf = a * s1_buf / (b + s2_buf) + c
            except:
                raise
            self.out_buf[i, 0:] = \
         clip_result(self.numtype, temp_buf).astype(self.numtype)
예제 #5
0
    def ReadAsArray(self,
                    xoff=0,
                    yoff=0,
                    win_xsize=None,
                    win_ysize=None,
                    buf_xsize=None,
                    buf_ysize=None,
                    buf_obj=None):
        import gdalnumeric

        return gdalnumeric.BandReadAsArray(self, xoff, yoff, win_xsize,
                                           win_ysize, buf_xsize, buf_ysize,
                                           buf_obj)
예제 #6
0
    def compute(self, *args):
        import re
        ex_exp = self.expression

        type = gdal.GetDataTypeByName(
            self.types_list[self.types.get_history()])
        numtype = gdalnumeric.GDALTypeCodeToNumericTypeCode(type)
        if numtype == None:
            gvutils.error("Error! Type " + numtype + " is not supported!")
            return FALSE

        fun_names_dict = {}
        fun_names_dict["max"] = ("maximum", 2)
        fun_names_dict["min"] = ("minimum", 2)
        fun_names_dict["asin"] = ("arcsin", 1)
        fun_names_dict["acos"] = ("arccos", 1)
        fun_names_dict["atan"] = ("arctan", 1)
        fun_names_dict["AND"] = ("bitwise_and", 2)
        fun_names_dict["OR"] = ("bitwise_or", 2)
        fun_names_dict["XOR"] = ("bitwise_xor", 2)
        fun_names_dict["inv"] = ("invert", 1)
        fun_names_dict["LShift"] = ("left_shift", 2)
        fun_names_dict["RShift"] = ("right_shift", 1)
        fun_names_dict['NDVI'] = ("self.NDVI", 2)

        sh_names_list = fun_names_dict.keys()
        for item in sh_names_list:
            ex_exp = re.sub(item, fun_names_dict[item][0], ex_exp)

        test_exp = ex_exp
        test_array = Numeric.zeros((1, 5), numtype)
        for i in range(len(self.list_of_bands)):
            patt_i = "%" + str(i + 1)
            repl_i = "sb[" + str(i) + "]"
            ex_exp = re.sub(patt_i, repl_i, ex_exp)
            test_exp = re.sub(patt_i, "test_array", test_exp)
        ex_exp = "rb=" + ex_exp
        test_exp = "test_res=" + test_exp

        try:
            exec test_exp
        except:
            gvutils.error("Illegal expression!")
            return FALSE

        if self.switch_new_view.get_active():
            gview.app.new_view()

        b1_name = self.list_of_bands[self.s1_list.get_history()]
        band_list = []
        for i in range(len(self.list_of_bands)):
            band_list.append(self.get_band(self.list_of_bands[i]))
        b1 = self.get_band(b1_name)
        proto_ds = self.dict_of_bands[b1_name][1].get_parent().get_dataset()
        self.out_buf = Numeric.zeros((b1.YSize, b1.XSize), numtype)

        sb = range(len(self.list_of_bands))
        for y in range(b1.YSize):
            for i in range(len(self.list_of_bands)):
                sb[i] = \
                    gdalnumeric.BandReadAsArray(band_list[i],0,y,b1.XSize,1)[0]
            try:
                exec ex_exp
            except:
                gvutils.error("ZeroDivide?")
                return FALSE
            self.out_buf[y, 0:] = clip_result(numtype, rb).astype(numtype)

        res_ds = gdalnumeric.OpenArray(self.out_buf, proto_ds)
        gview.app.open_gdal_dataset(res_ds)
예제 #7
0
파일: isodata.py 프로젝트: lmarabi/tareeg
    def classify_cb(self, *args):
        if len(self.band_list_to_classify) < 2:
            return
        if self.metric_num == 0:
            distance = L1
        elif self.metric_num == 2:
            distance = L3
        else:
            distance = L2
        nClusters = int(self.clusters.get_text())
        minvol = int(self.min_volume.get_text())
        maxit = int(self.maxiter.get_text())
        movement_treshold = float(self.mov_treshold.get_text())
        nBands = len(self.band_list_to_classify)
        cl_table = ClassesTable(nBands)
        self.hide()

        gview.app.new_view()

        b1_name = self.sel_list.get_text(0, 0)
        band_list = self.band_list_to_classify
        b1 = self.get_band(b1_name)
        proto_ds = self.dict_of_bands[b1_name][1].get_parent().get_dataset()
        self.out_buf = zeros((b1.YSize, b1.XSize), UnsignedInt8)

        sb = range(len(band_list))
        cp = zeros(nBands)
        d_means = zeros(nClusters, Float)
        volumes = range(nClusters)

        centres = []
        disp = []
        maxVal = 256.
        ymax = b1.YSize / 20
        ys = 20
        max_percent_val = 11 * maxit * b1.YSize / 40
        cur_percent_val = 0
        for i in range(nClusters):
            centres.append(((ones(nBands, Float) * i) * maxVal) / nClusters)
            disp.append(zeros(nBands, Float))
        for kit in range(maxit):
            centres_s = []
            for i in range(len(centres)):
                volumes[i] = 0
                centres_s.append(zeros(nBands, Float))
            flag = 0
            nc = len(centres)
            if kit >= maxit / 2:
                ymax = b1.YSize
                ys = 1
            for yc in range(ymax):
                y = yc * ys
                for i in range(nBands):
                    sb[i] = gdalnumeric.BandReadAsArray(
                        band_list[i], 0, y, b1.XSize, 1)[0]

                rb = self.out_buf[y, 0:]
                for x in range(b1.XSize):
                    for i in range(nBands):
                        cp[i] = sb[i][x]
                    mind = 1e29
                    for i in range(nc):
                        d = distance(centres[i], cp)
                        if d < mind:
                            mind = d
                            ic = i
                    if rb[x] != ic:
                        rb[x] = ic
                        flag = 1
                    centres_s[ic] += cp
                    disp[ic] += cp * cp
                    volumes[ic] += 1
                    if (distance == L2):
                        d_means[ic] += sqrt(mind)
                    else:
                        d_means[ic] += mind
                self.out_buf[y, 0:] = rb
                if y % 2 == 0:
                    cur_percent_val += 1
                    cl_table.show_progress(
                        100. * cur_percent_val / max_percent_val, y)
            ##########################################################
            new_centres = []
            d_tresh = sum(d_means) / sum(volumes)
            for i in range(len(centres)):
                cur_vol = volumes[i]
                if cur_vol > minvol / ys:
                    cur_centre = centres_s[i] / cur_vol
                    disp[i] = disp[i] / cur_vol - cur_centre * cur_centre
                    disp[i] = sqrt(disp[i])
                    d_means[i] /= cur_vol
                    if len(
                            centres
                    ) < nClusters and cur_vol > 2 * minvol / ys and d_means[
                            i] > d_tresh:
                        new_centres.append(cur_centre - disp[i])
                        new_centres.append(cur_centre + disp[i])
                    else:
                        new_centres.append(cur_centre)

            ncl = len(new_centres)
            if ncl > nClusters:
                mind = 1e29
                for i in range(ncl):
                    for j in range(i):
                        d = distance(new_centres[i], new_centres[j])
                        if d < mind:
                            mind = d
                            i1 = i
                            i2 = j
                new_centres[i1] += new_centres[i2]
                new_centres[i1] /= 2
                new_centres.remove(new_centres[i2])

            cl_table.set_data(new_centres, kit)

            if cl_table.stop_pressed():
                if ys > 1:
                    ymax = b1.YSize
                    ys = 1
                else:
                    break  #stop_pressed

            if len(centres) == len(new_centres):
                movement_flag = 0
                for i in range(len(centres)):
                    d = distance(centres[i], new_centres[i])
                    d /= d_tresh
                    if d > movement_treshold:
                        movement_flag = 1

                if movement_flag == 0:
                    if ys > 1:
                        ymax = b1.YSize
                        ys = 1
                    else:
                        break  # centres movement less then treshold

            centres = new_centres
            disp = []
            for i in range(len(centres)):
                disp.append(zeros(nBands, Float))
            volumes = zeros(len(centres))
            d_means = zeros(len(centres))

            if flag == 0:
                if ys > 1:
                    ymax = b1.YSize
                    ys = 1
                else:
                    break  #no changed points

        cl_table.finish()
        res_ds = gdalnumeric.OpenArray(self.out_buf, proto_ds)
        gview.app.open_gdal_dataset(res_ds)
        self.close()
예제 #8
0
def create_dist_map(rasterSrc,
                    vectorSrc,
                    npDistFileName='',
                    noDataValue=0,
                    burn_values=1,
                    dist_mult=1,
                    vmax_dist=64):
    '''
    Create building signed distance transform from Yuan 2016 
    (https://arxiv.org/pdf/1602.06564v1.pdf).
    vmax_dist: absolute value of maximum distance (meters) from building edge
    Adapted from createNPPixArray in labeltools
    '''

    ## open source vector file that truth data
    source_ds = ogr.Open(vectorSrc)
    source_layer = source_ds.GetLayer()

    ## extract data from src Raster File to be emulated
    ## open raster file that is to be emulated
    srcRas_ds = gdal.Open(rasterSrc)
    cols = srcRas_ds.RasterXSize
    rows = srcRas_ds.RasterYSize

    geoTrans, poly, ulX, ulY, lrX, lrY = gT.getRasterExtent(srcRas_ds)
    transform_WGS84_To_UTM, transform_UTM_To_WGS84, utm_cs \
                                        = gT.createUTMTransform(poly)
    line = ogr.Geometry(ogr.wkbLineString)
    line.AddPoint(geoTrans[0], geoTrans[3])
    line.AddPoint(geoTrans[0] + geoTrans[1], geoTrans[3])

    line.Transform(transform_WGS84_To_UTM)
    metersIndex = line.Length()

    memdrv = gdal.GetDriverByName('MEM')
    dst_ds = memdrv.Create('', cols, rows, 1, gdal.GDT_Byte)
    dst_ds.SetGeoTransform(srcRas_ds.GetGeoTransform())
    dst_ds.SetProjection(srcRas_ds.GetProjection())
    band = dst_ds.GetRasterBand(1)
    band.SetNoDataValue(noDataValue)

    gdal.RasterizeLayer(dst_ds, [1], source_layer, burn_values=[burn_values])
    srcBand = dst_ds.GetRasterBand(1)

    memdrv2 = gdal.GetDriverByName('MEM')
    prox_ds = memdrv2.Create('', cols, rows, 1, gdal.GDT_Int16)
    prox_ds.SetGeoTransform(srcRas_ds.GetGeoTransform())
    prox_ds.SetProjection(srcRas_ds.GetProjection())
    proxBand = prox_ds.GetRasterBand(1)
    proxBand.SetNoDataValue(noDataValue)

    opt_string = 'NODATA=' + str(noDataValue)
    options = [opt_string]

    gdal.ComputeProximity(srcBand, proxBand, options)

    memdrv3 = gdal.GetDriverByName('MEM')
    proxIn_ds = memdrv3.Create('', cols, rows, 1, gdal.GDT_Int16)
    proxIn_ds.SetGeoTransform(srcRas_ds.GetGeoTransform())
    proxIn_ds.SetProjection(srcRas_ds.GetProjection())
    proxInBand = proxIn_ds.GetRasterBand(1)
    proxInBand.SetNoDataValue(noDataValue)
    opt_string2 = 'VALUES=' + str(noDataValue)
    options = [opt_string, opt_string2]
    #options = ['NODATA=0', 'VALUES=0']

    gdal.ComputeProximity(srcBand, proxInBand, options)

    proxIn = gdalnumeric.BandReadAsArray(proxInBand)
    proxOut = gdalnumeric.BandReadAsArray(proxBand)

    proxTotal = proxIn.astype(float) - proxOut.astype(float)
    proxTotal = proxTotal * metersIndex
    proxTotal *= dist_mult

    # clip array
    proxTotal = np.clip(proxTotal, -1 * vmax_dist, 1 * vmax_dist)

    if npDistFileName != '':
        # save as numpy file since some values will be negative
        np.save(npDistFileName, proxTotal)
        #cv2.imwrite(npDistFileName, proxTotal)

    #return proxTotal
    return