Ejemplo n.º 1
0
def get_resampled_array_image(raster):
    raster_name = raster.replace('.jp2', 'resampled.jp2')
    raster_image = gdal.Open(raster, gdal.GA_Update)
    if raster_image is None:
        print('Raster image could not be opened...')
        print('Exiting the program...')
    band = raster_image.GetRasterBand(1)
    raster_array = band.ReadAsArray()
    drv = gdal.GetDriverByName("MEM")
    dst_ds = drv.Create("", raster_image.RasterXSize, raster_image.RasterYSize, \
                        1, gdal.GDT_UInt16)
    dst_ds.SetGeoTransform(raster_image.GetGeoTransform())
    dst_ds.SetProjection(raster_image.GetProjectionRef())
    dst_ds.GetRasterBand(1).WriteArray(raster_array)
    geoT = raster_image.GetGeoTransform()
    drv = gdal.GetDriverByName("GTiff")
    resampled_image = drv.Create(raster_name, \
                                 raster_image.RasterXSize * 2, raster_image.RasterYSize * 2, 1, gdal.GDT_UInt16)
    this_geoT = (geoT[0], geoT[1] / 2, geoT[2], geoT[3], \
                 geoT[4], geoT[5] / 2)
    resampled_image.SetGeoTransform(this_geoT)
    resampled_image.SetProjection(raster_image.GetProjectionRef())
    gdal.RegenerateOverviews(dst_ds.GetRasterBand(1), \
                             [resampled_image.GetRasterBand(1)], 'mode')
    resampled_image.GetRasterBand(1).SetNoDataValue(0)
    resampled_array = resampled_image.ReadAsArray()
    resampled_image = None
    return resampled_array
Ejemplo n.º 2
0
def _generate_mask_image(mask_path):
    """ Generates the mask and adapts the size to the original file."""
    mask_name = os.path.basename(mask_path)
    path_to_new_image = os.path.dirname(mask_path)
    mask_name_with_path = os.path.join(path_to_new_image, mask_name)
    mask = gdal.Open(mask_path, gdal.GA_Update)
    if mask is None:
        print('Mask image could not be opened...')
        print('Exiting the program...')
        sys.exit(1)
    mask_array = mask.ReadAsArray()
    mask_array[mask_array == 4] = 1
    mask_array[mask_array == 5] = 1
    mask_array[mask_array != 1] = 0
    drv = gdal.GetDriverByName("MEM")
    dst_ds = drv.Create("", mask.RasterXSize, mask.RasterYSize, \
                        1, gdal.GDT_UInt16)
    dst_ds.SetGeoTransform(mask.GetGeoTransform())
    dst_ds.SetProjection(mask.GetProjectionRef())
    dst_ds.GetRasterBand(1).WriteArray(mask_array)
    geoT = mask.GetGeoTransform()
    drv = gdal.GetDriverByName("GTiff")
    resampled_mask = drv.Create(mask_name_with_path, \
                                mask.RasterXSize * 2, mask.RasterYSize * 2, 1, gdal.GDT_UInt16)
    this_geoT = (geoT[0], geoT[1] / 2, geoT[2], geoT[3], \
                 geoT[4], geoT[5] / 2)
    resampled_mask.SetGeoTransform(this_geoT)
    resampled_mask.SetProjection(mask.GetProjectionRef())
    gdal.RegenerateOverviews(dst_ds.GetRasterBand(1), \
                             [resampled_mask.GetRasterBand(1)], 'mode')
    resampled_mask_array = resampled_mask.ReadAsArray()
    resampled_mask = None
    return resampled_mask_array
Ejemplo n.º 3
0
def _store_and_create_masked_raster_resampled(out_raster, raster):
    """ This function creates a resampled raster and stores it.
    """
    mask_name_with_path = raster
    image = gdal.Open(raster, gdal.GA_Update)
    if image is None:
        print('Mask image could not be opened...')
        print('Exiting the program...')
        sys.exit(1)
    drv = gdal.GetDriverByName("MEM")
    dst_ds = drv.Create("", image.RasterXSize, image.RasterYSize, 1,
                        gdal.GDT_UInt16)
    dst_ds.SetGeoTransform(image.GetGeoTransform())
    dst_ds.SetProjection(image.GetProjectionRef())
    dst_ds.GetRasterBand(1).WriteArray(out_raster)
    geoT = image.GetGeoTransform()
    drv = gdal.GetDriverByName("GTiff")
    resampled_image = drv.Create(mask_name_with_path, \
                                image.RasterXSize, image.RasterYSize, 1, gdal.GDT_UInt16)
    this_geoT = (geoT[0], geoT[1], geoT[2], geoT[3], \
                 geoT[4], geoT[5])
    resampled_image.SetGeoTransform(this_geoT)
    resampled_image.SetProjection(image.GetProjectionRef())
    gdal.RegenerateOverviews(dst_ds.GetRasterBand(1), \
                             [resampled_image.GetRasterBand(1)], 'mode')
    resampled_image.GetRasterBand(1).SetNoDataValue(0)
    band_1 = resampled_image.GetRasterBand(1)
    raster_array = band_1.ReadAsArray()
    raster_array[raster_array == -999] = 0
    band_1.WriteArray(raster_array)
    projection = osr.SpatialReference()
    projection.ImportFromWkt(resampled_image.GetProjectionRef())
    resampled_image = None
Ejemplo n.º 4
0
    def resample(self, cellsize_n, method='bilinear'):
        """
        resample the raster to a new cellsize
        cellsize_n: cellsize of the new raster
        method: Resampling method to use. Available methods are:
            near: nearest neighbour resampling (default, fastest algorithm, 
                                                worst interpolation quality).        
            bilinear: bilinear resampling.        
            cubic: cubic resampling.        
            cubicspline: cubic spline resampling.        
            lanczos: Lanczos windowed sinc resampling.        
            average: average resampling, computes the average of all 
                    non-NODATA contributing pixels.        
            mode: mode resampling, selects the value which appears most often 
                    of all the sampled points.        
            max: maximum resampling, selects the maximum value from all 
                    non-NODATA contributing pixels.        
            min: minimum resampling, selects the minimum value from all 
                    non-NODATA contributing pixels.        
            med: median resampling, selects the median value of all 
                    non-NODATA contributing pixels.        
            q1: first quartile resampling, selects the first quartile 
                value of all non-NODATA contributing pixels.        
            q3: third quartile resampling, selects the third quartile 
                value of all non-NODATA contributing pixels
        """
        from osgeo import gdal
        cellSize = self.header['cellsize']
        ras_x_size = self.header['ncols']
        newras_x_size = int(ras_x_size * cellSize / cellsize_n)
        rasterYSize = self.header['nrows']
        newRasterYSize = int(rasterYSize * cellSize / cellsize_n)

        g = self.to_osgeo_raster()  # get original gdal dataset
        total_obs = g.RasterCount
        drv = gdal.GetDriverByName("MEM")
        dst_ds = drv.Create('',
                            g.RasterXSize,
                            g.RasterYSize,
                            1,
                            eType=gdal.GDT_Float32)
        dst_ds.SetGeoTransform(g.GetGeoTransform())
        dst_ds.SetProjection(g.GetProjectionRef())
        hires_data = self.array
        dst_ds.GetRasterBand(1).WriteArray(hires_data)

        geo_trans_v = g.GetGeoTransform()
        drv = gdal.GetDriverByName("MEM")
        resampled_ds = drv.Create('',
                                  newras_x_size,
                                  newRasterYSize,
                                  1,
                                  eType=gdal.GDT_Float32)

        geo_trans_v_new = (geo_trans_v[0], cellsize_n, geo_trans_v[2],
                           geo_trans_v[3], geo_trans_v[3], -cellsize_n)
        resampled_ds.SetGeoTransform(geo_trans_v_new)
        resampled_ds.SetProjection(g.GetProjectionRef())
        resampled_ds.SetMetadata({"TotalNObs": "%d" % total_obs})

        gdal.RegenerateOverviews(dst_ds.GetRasterBand(1),
                                 [resampled_ds.GetRasterBand(1)], method)

        resampled_ds.GetRasterBand(1).SetNoDataValue(
            self.header['NODATA_value'])

        new_obj = self.__osgeo2raster(resampled_ds)
        resampled_ds = None

        return new_obj
Ejemplo n.º 5
0
 def transform(self, *args):
     """
     georeference raster from more point coordinates
     args = [(x1,y1),(x2,y2),(xn,yn)] or (x1,y1),(x2,y2),(xn,yn)
     """
     if len(args) == 1 and type(args[0]) is list:
         args = args[0]
     # test projection
     if self.Projection == '':
         raise Exception('projection for georeference not found')
     # warp raster to new projection
     if args == () and self.Projection != self.raster.Projection:
         # create mask array
         if self.nodata is not None:
             mask = array2raster(
                 None, {
                     "array":
                     np.full((self.raster.rows, self.raster.cols),
                             self.warp_mask,
                             dtype=self.raster.codage),
                     "shape": (self.raster.rows, self.raster.cols),
                     "transform": (self.raster.TL_x, self.raster.x_res,
                                   self.raster.x_diff, self.raster.TL_y,
                                   self.raster.y_diff, self.raster.y_res),
                     "projection":
                     self.raster.Projection,
                     "nodata":
                     None,
                 })
             mask = array2raster(
                 gdal.AutoCreateWarpedVRT(
                     mask.Ds,
                     None,
                     self.Projection,
                     self.warp_resampling,
                     self.warp_error_threshold,
                 ), None)
             mask = mask.array()
         else:
             mask = None
         # warping
         self.raster = array2raster(
             gdal.AutoCreateWarpedVRT(
                 self.raster.Ds,
                 None,
                 self.Projection,
                 self.warp_resampling,
                 self.warp_error_threshold,
             ), None, False, self.band_num)
         # enter mask
         if mask is not None:
             rarray = self.raster.array()
             self.raster = array2raster(
                 None, {
                     "array":
                     np.where(mask == self.warp_mask, rarray, self.nodata),
                     "shape": (self.raster.rows, self.raster.cols),
                     "transform": (self.raster.TL_x, self.raster.x_res,
                                   self.raster.x_diff, self.raster.TL_y,
                                   self.raster.y_diff, self.raster.y_res),
                     "projection":
                     self.raster.Projection,
                     "nodata":
                     self.raster.nodata,
                 })
             del (rarray)
             mask = None
     # input params
     _cols = self.raster.cols
     _rows = self.raster.rows
     _GeoTransform = self.raster.GeoTransform
     _TL_x = float(_GeoTransform[0])
     _x_res = float(_GeoTransform[1])
     _x_diff = float(_GeoTransform[2])
     _TL_y = float(_GeoTransform[3])
     _y_res = float(_GeoTransform[5])
     _y_diff = float(_GeoTransform[4])
     # transform parms
     if args == ():
         UL_x = _TL_x
         UL_y = _TL_y
         LR_x = None
         LR_y = None
     else:
         x_array = [float(my[0]) for my in args]
         y_array = [float(my[1]) for my in args]
         UL_x = min(x_array)
         UL_y = max(y_array)
         LR_x = max(x_array)
         LR_y = min(y_array)
     # find x_res
     if _x_res == 1.0 and LR_x is None:
         raise Exception('coordinates for georeference not found')
     if LR_x is not None:
         x_res = float((LR_x - UL_x) / self.cols)
     else:
         x_res = float((_x_res * _cols) / self.cols)
     # find y_res
     if _y_res == 1.0 and LR_y is None:
         raise Exception('coordinates for georeference not found')
     if LR_y is not None:
         y_res = float((LR_y - UL_y) / self.rows)
     else:
         y_res = float((_y_res * _rows) / self.rows)
     x_diff = _x_diff
     y_diff = _y_diff
     # create transform raster
     t_raster = array2raster(
         None, {
             "array": None,
             "shape": (self.rows, self.cols),
             "transform": (UL_x, x_res, x_diff, UL_y, y_diff, y_res),
             "projection": self.Projection,
             "nodata": self.raster.nodata,
         })
     # transformation
     gdal.RegenerateOverviews(self.raster.Band, [t_raster.Band], 'mode')
     # init value
     if t_raster.codage != self.codage: t_raster.codage = self.codage
     if t_raster.nodata != self.nodata: t_raster.nodata = self.nodata
     # reinit new value
     self.Ds = t_raster.Ds
     self.GeoTransform = self.Ds.GetGeoTransform()
     self.TL_x = float(self.GeoTransform[0])
     self.x_res = float(self.GeoTransform[1])
     self.x_diff = float(self.GeoTransform[2])
     self.TL_y = float(self.GeoTransform[3])
     self.y_res = float(self.GeoTransform[5])
     self.y_diff = float(self.GeoTransform[4])
     self.Projection = self.Ds.GetProjection()
     self.cols = self.Ds.RasterXSize
     self.rows = self.Ds.RasterYSize
     self.bands = self.Ds.RasterCount
     self.Band = self.Ds.GetRasterBand(1)