def __init__(self, filename): self.filename = filename ds = gdal.Open(filename) self.txf = ds.GetGeoTransform() # Handles difference in return from gdal.InvGeoTransform between gdal version 1 and 2 gdal_version = osgeo.gdal.__version__ if gdal_version[0] == '1': self.inv_txf = gdal.InvGeoTransform(self.txf)[1] else: self.inv_txf = gdal.InvGeoTransform(self.txf) wgs84_ref = osr.SpatialReference() wgs84_ref.ImportFromEPSG(4326) sref = osr.SpatialReference() sref.ImportFromWkt(ds.GetProjection()) self.width = ds.RasterXSize self.height = ds.RasterYSize self.transform = osr.CoordinateTransformation(wgs84_ref, sref) self.inv_transform = osr.CoordinateTransformation(sref, wgs84_ref) #print self.txf self.coord_bounds = [ self.txf[0], # upper left x self.txf[3], # upper left y self.txf[0] + self.txf[1] * ds.RasterXSize + self.txf[2] * ds.RasterYSize, # lower right x self.txf[3] + self.txf[4] * ds.RasterXSize + self.txf[5] * ds.RasterYSize # lower right y ] # Find the corners of the tile for examining lat/lng to find intersection with tile. corners = [] for x in [0, ds.RasterXSize]: for y in [0, ds.RasterYSize]: corners.append([ self.txf[0] + self.txf[1] * x + self.txf[2] * y, self.txf[3] + self.txf[4] * x + self.txf[5] * y ]) # TODO: does this account for 180-crossing tiles? self.max_lat = -100 self.min_lat = 100 self.max_lng = -500 self.min_lng = 500 for c in corners: p = self.inv_transform.TransformPoint(c[0], c[1]) if p[0] > self.max_lng: self.max_lng = p[0] if p[0] < self.min_lng: self.min_lng = p[0] if p[1] > self.max_lat: self.max_lat = p[1] if p[1] < self.min_lat: self.min_lat = p[1] # Close file ds = None
def __init__(self, tile_path): """Initializes the Tile Information. Inputs: tile_path: path the tile file. """ self.tile_path = tile_path ds = gdal.Open(tile_path) self.width = ds.RasterXSize self.height = ds.RasterYSize # Gets the gdal geo transformation tuples gdal_version = osgeo.gdal.__version__ self._txf = ds.GetGeoTransform() if gdal_version[0] == '1': self._inv_txf = gdal.InvGeoTransform(self._txf)[1] else: self._inv_txf = gdal.InvGeoTransform(self._txf) # Gets the transformation from lat/lon to coordinates wgs84_ref = osr.SpatialReference() wgs84_ref.ImportFromEPSG(4326) # WGS84 sref = osr.SpatialReference() sref.ImportFromWkt(ds.GetProjection()) self._transform = osr.CoordinateTransformation(wgs84_ref, sref) inv_transform = osr.CoordinateTransformation(sref, wgs84_ref) # Find a loose lat/lon bounding box for quick check without # having to do full coordinates transformation corners = [] for x in [0, self.width]: for y in [0, self.height]: corners.append([self._txf[0] + self._txf[1] * x + self._txf[2] * y, self._txf[3] + self._txf[4] * x + self._txf[5] * y]) self.max_lat = -100 self.min_lat = 100 self.max_lon = -500 self.min_lon = 500 for c in corners: p = inv_transform.TransformPoint(c[0], c[1]) if p[0] > self.max_lon: self.max_lon = p[0] if p[0] < self.min_lon: self.min_lon = p[0] if p[1] > self.max_lat: self.max_lat = p[1] if p[1] < self.min_lat: self.min_lat = p[1] # Close file ds = None
def __init__(self, fname): """ :param fname: a GTif file """ try: self.raster = gdal.Open(fname) spatial_ref = osr.SpatialReference(self.raster.GetProjection()) # retrieve get the WGS84 spatial reference wgs_ref = osr.SpatialReference() wgs_ref.ImportFromEPSG(4326) # Do a coordinate transform self.coord_transf = osr.CoordinateTransformation( wgs_ref, spatial_ref) # Apply geo-transformation and its inverse self.raster_gt = self.raster.GetGeoTransform() self.raster_inv_gt = gdal.InvGeoTransform(self.raster_gt) # Handle error from Inverse function if gdal.VersionInfo()[0] == '1': if self.raster_inv_gt[0] == 1: self.raster_inv_gt = self.raster_inv_gt[1] else: raise RuntimeError('Inverse geotransform failed') elif self.raster_inv_gt is None: raise RuntimeError('Inverse geotransform failed') except RuntimeError: # <- Check first what exception is being thrown pass
def LoadTileForLatLng(self, lat, lng): latf = int(math.ceil(lat)) lngf = int(math.floor(lng)) k = '%s.%s' % (latf, lngf) if k in self.tile_cache: return filename = self.latlng_file[k] print 'Loading tile %s from %s' % (k, filename) dataset = gdal.Open(filename) # Store the inverse geo transform which will map (lat, lng) to array indices # in this tile. tx = dataset.GetGeoTransform() self.txf[k] = gdal.InvGeoTransform(tx) self.tile_cache[k] = dataset.ReadAsArray().astype(numpy.float) self.tile_lru[k] = time.clock() # evict a tile if there are more than tile_lru_size elements in the cache if len(self.tile_lru) > self.tile_lru_size: mint = 0 mink = '' for k in self.tile_lru.keys(): if self.tile_lru[k] > mint: mint = self.tile_lru[k] mink = k print 'Evicting tile %s' % k del self.tile_cache[k] del self.tile_lru[k] # close the file dataset = None
def create_geotransform(self, x_rotation=0, y_rotation=0): '''Create geotransformation for converting 2D projected point from pixels and inverse geotransformation to pixels (what I want, but need the geotransform first).''' # TODO make sure this works with negative & positive lons top_left_x, top_left_y = self.transform_point(min(self.x), max(self.y)) lower_right_x, lower_right_y = self.transform_point( max(self.x), min(self.y)) # GeoTransform parameters # --> need to know the area that will be covered to define the geo tranform # top left x, w-e pixel resolution, rotation, top left y, rotation, n-s pixel resolution # NOTE: cell height must be negative (-) to apply image space to map geotransform = [ top_left_x, self.cellh, x_rotation, top_left_y, y_rotation, -self.cellh ] # for mapping lat/lon to pixel success, inverse_geotransform = gdal.InvGeoTransform(geotransform) if not success: print 'gdal.InvGeoTransform(geotransform) failed!' sys.exit(1) return geotransform, inverse_geotransform
def lasToRaster(las_filename, transform, shape_out, NODATA): # Load LAS file test_las = File(las_filename, mode='r') x = test_las.x y = test_las.y z = test_las.z # Project to output image space # TODO: call map2pix map_to_pix = gdal.InvGeoTransform(transform) x0 = np.round(map_to_pix[0] + x * map_to_pix[1] + y * map_to_pix[2]) y0 = np.round(map_to_pix[3] + x * map_to_pix[4] + y * map_to_pix[5]) x0 = x0.astype(int) y0 = y0.astype(int) # Generate MAX value DSM raster = np.zeros(shape_out, np.float32) + NODATA for ii in range(0, x0.size): if (x0[ii] >= 0) & (x0[ii] < raster.shape[1]) & (y0[ii] >= 0) & ( y0[ii] < raster.shape[0]): if z[ii] > raster[y0[ii], x0[ii]]: raster[y0[ii], x0[ii]] = z[ii] return raster
def check_vals(data,affine,points=TEST_POINTS): inv_a = Affine.from_gdal(*gdal.InvGeoTransform(affine.to_gdal())) for (coords,val) in points: [col_f,row_f] = inv_a*coords[::-1] [col,row] = [int(col_f),int(row_f)] assert data[row,col]==val
def load_map(filename): dataset = gdal.Open(filename) data = dataset.ReadAsArray() _, height, width = data.shape geo_trans = dataset.GetGeoTransform() inv_trans = gdal.InvGeoTransform(geo_trans) img = mpimg.imread(filename) return img, inv_trans, geo_trans, width, height
def image_offsets(img, coordinates): gt = img.GetGeoTransform() inv_gt = gdal.InvGeoTransform(gt) offsets_ul = list( map(int, gdal.ApplyGeoTransform(inv_gt, coordinates[0], coordinates[1]))) offsets_lr = list( map(int, gdal.ApplyGeoTransform(inv_gt, coordinates[2], coordinates[3]))) return offsets_ul + offsets_lr
def RasterOverlapToArray(file_list): UL_x_list = [] UL_y_list = [] LR_x_list = [] LR_y_list = [] for file in file_list: ds = gdal.Open(root_folder + file, gdal.GA_ReadOnly) gt = ds.GetGeoTransform( ) # UL_x, x-coordinate spatial resolution, UL_y, # y-coord. spat.res. # Upper left UL_x, UL_y = gt[0], gt[ 3] #calculate corner lat/lon coordinates (for x/y cell coordinates use inv_gt) UL_x_list.append(UL_x) UL_y_list.append(UL_y) # Lower right LR_x = UL_x + (gt[1] * ds.RasterXSize) LR_y = UL_y + (gt[5] * ds.RasterYSize) LR_x_list.append(LR_x) LR_y_list.append(LR_y) UL_x_ext = max(UL_x_list) #corner coordinates and extent of common extent UL_y_ext = min(UL_y_list) LR_x_ext = min(LR_x_list) LR_y_ext = max(LR_y_list) extent_x = int(round( (min(LR_x_list) - max(UL_x_list)) / gt[1])) #width of common extent/pixel width = number of columns extent_y = int( round(min(UL_y_list) - max(LR_y_list)) / gt[1]) #height of common extent/pixel height = number of rows overlap = [UL_x_ext, UL_y_ext, LR_x_ext, LR_y_ext] #only upper left and lower right coordinates print("Common extent UL/LR coordinates: ", overlap) print("Common extent in x and y direction: ", extent_x, extent_y) spat_res = [gt[1], abs(gt[5])] print("Common extent spatial resolution: ", spat_res, "\n") for file in file_list: #convert real-world coordinates (lat/lon) to image coordinates (x,y) print(file) #for overview in console ds = gdal.Open(root_folder + file, gdal.GA_ReadOnly) gt = ds.GetGeoTransform( ) # UL_x, x-coordinate spatial resolution, UL_y, # y-coord. spat.res. inv_gt = gdal.InvGeoTransform( gt) # transform geographic coordinates into array coordinates x1, y1 = gdal.ApplyGeoTransform(inv_gt, overlap[0], overlap[1]) x2, y2 = gdal.ApplyGeoTransform(inv_gt, overlap[2], overlap[3]) minX = int(round(min(x1, x2))) # x value for UL/origin minY = int(round(min(y1, y2))) # y value for UL/origin maxX = int(round(max(x1, x2))) # x value for LR maxY = int(round(max(y1, y2))) # y value for LR print("Cell coordinates of common extent: ", minX, maxX, minY, maxY) #cell coordinates of extent for each file x1off, y1off = map(int, [x1, y1]) #UL print("UL x offset: ", x1off) print("UL y offset: ", y1off, "\n") array_list.append(ds.ReadAsArray(x1off, y1off, extent_x, extent_y)) #Upper Left corner
def set_geot( self, geo_t # type: list ): # type: (...) -> None """ sets the geotiffs geotransform and inverse geotransform :param geo_t: geotransform specified by gdal's documentation. :return: None """ self._geo_t = geo_t self._inv_geo_t = gdal.InvGeoTransform(geo_t)
def getcolrow(self, ds, lon, lat): proj = ds.GetProjection() src = osr.SpatialReference() src.ImportFromEPSG(4326) dest = osr.SpatialReference() dest.ImportFromWkt(proj) trans = osr.CoordinateTransformation(src, dest) x, y, z = trans.TransformPoint(lon, lat) inv = gdal.InvGeoTransform(ds.GetGeoTransform()) return gdal.ApplyGeoTransform(inv, x, y)
def create_raster(lons, lats, filename="Utils/raster/montserrat-dem.vrt", output_format="MEM"): x_rotation = 0 y_rotation = 0 cell_width_meters = 15.0 cell_height_meters = 15.0 # retrieve bounds for point data min_lon, max_lon, min_lat, max_lat = get_iterable_extent(lons, lats) # Fa transformacions al sistema de coordenades # Set geographic coordinate system to handle lat/lon srs = osr.SpatialReference() srs.SetWellKnownGeogCS("WGS84") # Set projected coordinate system to handle meters wgs84_obj = WGS84Transform() srs.SetUTM(wgs84_obj.get_utm_zone(min_lon), wgs84_obj.is_lat_northern(max_lat)) # create transforms for point conversion wgs84_coordinate_system = srs.CloneGeogCS() # clone only the geographic coordinate system wgs84_to_utm_transform = osr.CoordinateTransformation(wgs84_coordinate_system, srs) utm_to_wgs84_transform = osr.CoordinateTransformation(srs, wgs84_coordinate_system) # convert bounds to UTM top_left_x, top_left_y, z = wgs84_obj.wgs84_to_utm(min_lon, max_lat) lower_right_x, lower_right_y, z = wgs84_obj.wgs84_to_utm(max_lon, min_lat) # Llegim el model d'elevacions (met[..].txt) dataset = gdal.Open(filename, gdal.GA_Update) # Llegim la transformacio del fitxer geo_transform = dataset.GetGeoTransform() # Assignem la projeccio dataset.SetProjection(srs.ExportToWkt()) # Fem la inversa de la transformacio per passar de lat/lon a pixel inverse_geo_transform = gdal.InvGeoTransform(geo_transform) # agafem la banda raster del fitxer band = dataset.GetRasterBand(1) # 1 == band index value eles = [] for lon, lat in zip(lons, lats): # zip: estructura de dades rollo map, iterem sobre els vectors lat i lon alhora pixel_x, pixel_y = lonlat_to_pixel(lon, lat, inverse_geo_transform) # convertim lat/lon a pixel scanline = band.ReadAsArray(pixel_x, pixel_y, 1, 1, 1, 1) # llegim el pixel al fitxer eles.append(scanline) # set dataset to None to "close" file dataset = None return eles
def get_cached_value(self, filename, lon, lat): """ Get a single value at (lon,lat) from cache """ path = os.path.join(self.cache, filename) ds = gdal.OpenShared(path) fwd = ds.GetGeoTransform() inv = gdal.InvGeoTransform(fwd) # older versions of gdal have a different signature of InvGeoTransform() if inv and len(inv) == 2: _success, inv = inv x, y = gdal.ApplyGeoTransform(inv, lon, lat) x = int(max(0, min(ds.RasterXSize - 1, x))) y = int(max(0, min(ds.RasterYSize - 1, y))) value = ds.GetRasterBand(1).ReadAsArray(x, y, 1, 1) return value[0][0]
def transbox(self, ds, bbox, topix=False, clip=False): ''' transform bounding box coordinates in lonlat to projected coordinates or pixel coordinates ''' src = osr.SpatialReference() src.ImportFromEPSG(4326) dest = osr.SpatialReference() dsproj = ds.GetProjection() dest.ImportFromWkt(dsproj) trans = osr.CoordinateTransformation(src, dest) x1, y1, x2, y2 = bbox ll = trans.TransformPoint(x1, y1) ul = trans.TransformPoint(x1, y2) lr = trans.TransformPoint(x2, y1) ur = trans.TransformPoint(x2, y2) x1 = min(ll[0], ul[0]) x2 = max(lr[0], ur[0]) y1 = min(ll[1], lr[1]) y2 = max(ul[1], ur[1]) if clip or topix: fwd = ds.GetGeoTransform() inv = gdal.InvGeoTransform(fwd) px1, py1 = gdal.ApplyGeoTransform(inv, x1, y1) px2, py2 = gdal.ApplyGeoTransform(inv, x2, y2) if py1 > py2: t = py1 py1 = py2 py2 = t if clip: px1 = int(max(0, px1)) py1 = int(max(0, py1)) px2 = int(min(ds.RasterXSize - 1, px2)) py2 = int(min(ds.RasterYSize - 1, py2)) if topix: x1 = px1 y1 = py1 x2 = px2 y2 = py2 else: x1, y1 = gdal.ApplyGeoTransform(fwd, px1, py1) x2, y2 = gdal.ApplyGeoTransform(fwd, px2, py2) if y1 > y2: return (x1, y2, x2, y1) else: return (x1, y1, x2, y2)
def image_offsets(img, coordinates): ''' Function that calculates the image offsets from the upper left and lower right corners. :param img: :param coordinates: :return: ''' gt = img.GetGeoTransform() inv_gt = gdal.InvGeoTransform(gt) offsets_ul = list( map(int, gdal.ApplyGeoTransform(inv_gt, coordinates[0], coordinates[1]))) offsets_lr = list( map(int, gdal.ApplyGeoTransform(inv_gt, coordinates[2], coordinates[3]))) return offsets_ul + offsets_lr
def __init__(self, fname): self.dataset = gdal.Open(fname, gdal.GA_ReadOnly) #print 'opened',self.dataset.GetDescription() self.band = self.dataset.GetRasterBand(1) self.geoTransform = self.dataset.GetGeoTransform() self.inverseGeoTransorm = gdal.InvGeoTransform(self.geoTransform) #print self.geoTransform self.data = self.band.ReadAsArray() #print self.data.shape sourceSR = gdal.osr.SpatialReference() sourceSR.SetWellKnownGeogCS("WGS84") targetSR = gdal.osr.SpatialReference() targetSR.ImportFromWkt(self.dataset.GetProjection()) self.coordinateTransformation = gdal.osr.CoordinateTransformation(sourceSR, targetSR)
def __init__(self, file_name): self._fmttypes = { gdalconst.GDT_Byte: 'B', gdalconst.GDT_Int16: 'h', gdalconst.GDT_UInt16: 'H', gdalconst.GDT_Int32: 'i', gdalconst.GDT_UInt32: 'I', gdalconst.GDT_Float32: 'f', gdalconst.GDT_Float64: 'f' } self.ds = gdal.Open(file_name, gdalconst.GA_ReadOnly) if self.ds is None: raise FileNotFoundError(file_name) self.transf = self.ds.GetGeoTransform() self.cols = self.ds.RasterXSize self.rows = self.ds.RasterYSize self.bands = self.ds.RasterCount self.transfInv = gdal.InvGeoTransform(self.transf)
def get_weights(self, ds, geom): fwd = ds.GetGeoTransform() _, inv = gdal.InvGeoTransform(fwd) x1, x2, y1, y2 = geom.GetEnvelope() px1, py1 = gdal.ApplyGeoTransform(inv, x1, y1) px2, py2 = gdal.ApplyGeoTransform(inv, x2, y2) if py2 < py1: t = py1 py1 = py2 py2 = t px1 = max(0, px1) py1 = max(0, py1) px2 = min(ds.RasterXSize, px2) py2 = min(ds.RasterYSize, py2) if px2 < px1 or py2 < py1: return [] weights = [] for y in range(int(py1), int(py2)): for x in range(int(px1), int(px2)): x1, y1 = gdal.ApplyGeoTransform(fwd, x, y) x2, y2 = gdal.ApplyGeoTransform(fwd, x + 1, y + 1) ring = ogr.Geometry(ogr.wkbLinearRing) ring.AddPoint(x1, y1) ring.AddPoint(x1, y2) ring.AddPoint(x2, y2) ring.AddPoint(x2, y1) ring.AddPoint(x1, y1) poly = ogr.Geometry(ogr.wkbPolygon) poly.AddGeometry(ring) if geom.Contains(poly): frac = 1.0 else: isect = poly.Intersection(geom) if isect.IsEmpty(): frac = 0.0 else: frac = isect.GetArea() / poly.GetArea() if frac != 0: weights.append([x, y, frac]) return weights
def lonlat2xy(name,lon,lat): ds=gdal.Open(name) xoffset, px_w, rot1, yoffset, rot2, px_h = ds.GetGeoTransform() print 'xoff, dx, rot1, yoff, dy, rot2',xoffset, px_w, rot1, yoffset, px_h, rot2 t = osr.CoordinateTransformation(crs_ref(),crs_ds(ds)) posX, posY, z = t.TransformPoint(lat,lon,0) posX -= px_w / 2.0 posY -= px_h / 2.0 transform = ds.GetGeoTransform() gt = [transform[0],transform[1],0,transform[3],0,transform[5]] inverse_gt = gdal.InvGeoTransform(gt) x = inverse_gt[0] + inverse_gt[1] * posX + inverse_gt[2] * posY y = inverse_gt[3] + inverse_gt[4] * posX + inverse_gt[5] * posY return x,y
def misc_7(): try: gdal.InvGeoTransform except: return 'skip' gt = (10, 0.1, 0, 20, 0, -1.0) res = gdal.InvGeoTransform(gt) if res[0] != 1: print(res) return 'fail' expected_inv_gt = (-100.0, 10.0, 0.0, 20.0, 0.0, -1.0) for i in range(6): if abs(res[1][i] - expected_inv_gt[i]) > 1e-6: print(res) return 'fail' return 'success'
def getRasterLayerValue(lon, lat, raster): """ Get the Raster cell value for the specified Latitude / Longitude. If the LL outside bounds of the raster, return NO_DATA_VALUE Note: see code in http://trac.osgeo.org/gdal/browser/trunk/gdal/swig/python/samples/val_at_coord.py """ # Build Spatial Reference object based on coordinate system, fetched from the # opened dataset srs = ogr.osr.SpatialReference() srs.ImportFromWkt(raster.GetProjection()) # DEVTODO: Make the SRS code for this function and the getVectorLayerAttrVal the same (?) srsLatLong = srs.CloneGeogCS() # Convert from (longitude,latitude) to projected coordinates ct = ogr.osr.CoordinateTransformation(srsLatLong, srs) (X, Y, height) = ct.TransformPoint(lon, lat) # Read geotransform matrix and calculate corresponding pixel coordinates geomatrix = raster.GetGeoTransform() (success, inv_geometrix) = gdal.InvGeoTransform(geomatrix) x = int(inv_geometrix[0] + inv_geometrix[1] * X + inv_geometrix[2] * Y) y = int(inv_geometrix[3] + inv_geometrix[4] * X + inv_geometrix[5] * Y) if x < 0 or x >= raster.RasterXSize or y < 0 or y >= raster.RasterYSize: # Passed coordinates are not in dataset extent return cc.NO_DATA_VALUE # DEVNOTE: TKR - The following line causes an Process Exit issue: "Process finished with exit code -1073741819 ( # 0xC0000005)". It does not seem to affect the proper execution of the program, but does cause a "messy" exit. I # tried to figure out a solution, but unable to. Some discussion of possible like issues at https://trac.osgeo.org/gdal/wiki/PythonGotchas res = raster.GetRasterBand(1).ReadAsArray(x, y, 1, 1) val = res[0][0] # No Data Value is a Float noData = raster.GetRasterBand(1).GetNoDataValue() if abs(val - noData) <= sys.float_info.epsilon: return cc.NO_DATA_VALUE else: return val
def subset(raster, subset, coordinates=True, multiband=False): """ Subsets a given raster to a set of coordinates [subset] into an array. When subset is given as list of geographic coordinates, they will be transformed to array indices. When subset is given as array indices, image will be subsetted. Indices must be in format [ulx, uly,lrx,lry] Bool-Arguments don't have to be specified, when called. Defaults to function definition. :param raster: :param subset: :param coordinates: :param multiband: :return array: """ if coordinates: gt = raster.GetGeoTransform() inv_gt = gdal.InvGeoTransform(gt) app_gt_offset_upperleft = gdal.ApplyGeoTransform( inv_gt, geo_overlap[0], geo_overlap[1]) app_gt_offset_lowerright = gdal.ApplyGeoTransform( inv_gt, geo_overlap[2], geo_overlap[3]) off_ulx, off_uly = map(int, app_gt_offset_upperleft) off_lrx, off_lry = map(int, app_gt_offset_lowerright) rows = off_lry - off_uly columns = off_lrx - off_ulx # idx = [off_ulx, off_uly, columns, rows ] array = raster.ReadAsArray(off_ulx, off_uly, columns, rows) return array else: idx = subset if gdal: array = raster.ReadAsArray(idx[0], idx[1], idx[2] - idx[0], idx[3] - idx[1]) else: if multiband: array = raster[:, idx[0]:idx[2], idx[1]:idx[3]] else: array = raster[idx[0]:idx[2], idx[1]:idx[3]] return array
def visible_region(self, geo_x=None, geo_y=None, width=None, height=None, scale=None): if self.raster is None: return if geo_x is None: geo_x = self.geo_x if geo_y is None: geo_y = self.geo_y if width is None: width = self.width() if height is None: height = self.height() if scale is None: scale = self.scale assert geo_x is not None and geo_y is not None geo_transform = self.raster.GetGeoTransform( ) # col, row ---> lon, lat ok, inverse_geo_transform = gdal.InvGeoTransform( geo_transform) # lon, lat ---> col, row col, row = gdal.ApplyGeoTransform(inverse_geo_transform, self.geo_x, self.geo_y) # col, row are now where we are centered in the image # I want scale=1 to be viewing the image at 1m per pixel. # The image may be sampled at a different resolution, fetch the meters-per-pixel from the geo-transform # Also, the pixels generally are not square. meters_x = geo_transform[1] meters_y = geo_transform[5] # Determine the size and offset within the raster x_size = abs(int(width * meters_x / scale)) y_size = abs(int(height * meters_y / scale)) x_off = int(col - x_size / 2) y_off = int(row - y_size / 2) return x_off, y_off, x_size, y_size
def CoordToIndex(geoTransform, x, y): """Return the offset of the provided co-ordinate from origin of raster""" invGeotransform = gdal.InvGeoTransform(geoTransform) x1, y1 = gdal.ApplyGeoTransform(invGeotransform, x, y) columnPosition, RowPosition = int(x1), int(y1) return (columnPosition, RowPosition)
ras2 = gdal.Open(indir + "LE07_L1TP_117056_20130627_20161124_01_T1_sr_evi.tif") ras2_b = ras2.GetRasterBand(1) ras3 = gdal.Open(indir + "LT05_L1TP_117056_19980407_20161228_01_T1_sr_evi.tif") ras3_b = ras3.GetRasterBand(1) ras4 = gdal.Open(indir + "LT05_L1TP_117056_20000717_20161214_01_T1_sr_evi.tif") ras4_b = ras4.GetRasterBand(1) sr_ras1 = SpatialReferenceFromRaster(ras1) sr_ras2 = SpatialReferenceFromRaster(ras2) sr_ras3 = SpatialReferenceFromRaster(ras3) sr_ras4 = SpatialReferenceFromRaster(ras4) sr_all = [sr_ras1, sr_ras2, sr_ras3, sr_ras4] gt_r1 = ras1.GetGeoTransform() inv_gt_r1 = gdal.InvGeoTransform(gt_r1) gt_r2 = ras2.GetGeoTransform() inv_gt_r2 = gdal.InvGeoTransform(gt_r2) gt_r3 = ras3.GetGeoTransform() inv_gt_r3 = gdal.InvGeoTransform(gt_r3) gt_r4 = ras4.GetGeoTransform() inv_gt_r4 = gdal.InvGeoTransform(gt_r4) # classification array inv_gt_all = [inv_gt_r1, inv_gt_r2, inv_gt_r3, inv_gt_r4] res_all = gt_r1[1] cols_all = round(int(result_list[3][1] - result_list[1][1]) / res_all) #cols_all
def rastersubbyCord(raster, ULx, ULy, LRx, LRy, storpath='none', nodata='fromimage'): # check storpath if storpath is not 'none': if storpath.endswith('/'): storpath = storpath else: storpath = storpath + '/' # check if raster is list if type(raster) is not list: raster = [raster] else: raster = raster k = ['Raster', 'ULx_off', 'ULy_off', 'LRx_off', 'LRy_off', 'Data'] v = [[], [], [], [], [], []] res = dict(zip(k, v)) for z, i in enumerate(raster): if type(i) is not gdal.Dataset: in_ds = gdal.Open(i) else: in_ds = i in_gt = in_ds.GetGeoTransform() inv_gt = gdal.InvGeoTransform(in_gt) # transform coordinates into offsets (in cells) and make them integer off_UpperLeft = gdal.ApplyGeoTransform( inv_gt, ULx, ULy ) # new UL * rastersize^-1 + original ul/rastersize(opposite sign off_LowerRight = gdal.ApplyGeoTransform(inv_gt, LRx, LRy) off_ULx, off_ULy = map(round, off_UpperLeft) # or int???????????????? off_LRx, off_LRy = map(round, off_LowerRight) in_band = in_ds.GetRasterBand(1) data = in_band.ReadAsArray(off_ULx, off_ULy, off_LRx - off_ULx, off_LRy - off_ULy) if storpath is not 'none': gtiff_driver = gdal.GetDriverByName('GTiff') out_ds = gtiff_driver.Create( storpath + (i.split('/')[-1]).split('.')[0] + '_subby.tif', off_LRx - off_ULx, off_LRy - off_ULy, 1, in_ds.GetRasterBand(1).DataType) out_gt = list(in_gt) out_gt[0], out_gt[3] = gdal.ApplyGeoTransform( in_gt, off_ULx, off_ULy) out_ds.SetGeoTransform(out_gt) out_ds.SetProjection(in_ds.GetProjection()) out_ds.GetRasterBand(1).WriteArray(data) if nodata is 'fromimage': out_ds.GetRasterBand(1).SetNoDataValue( in_band.GetNoDataValue()) else: out_ds.GetRasterBand(1).SetNoDataValue(nodata[z]) del out_ds a = [ i, off_ULx, off_ULy, off_LRx, off_LRy, np.where(data != nodata[z], data, np.nan) ] for t, j in enumerate(k): res[j].append(a[t]) cols = [ res['LRx_off'][i] - res['ULx_off'][i] for i, j in enumerate(raster) ] if len(set(cols)) > 1: print('') print("WARNING: subsets vary in x extent!!!!!!!!!!!!!!") print('') rows = [ res['LRy_off'][i] - res['ULy_off'][i] for i, j in enumerate(raster) ] if len(set(rows)) > 1: print('') print("WARNING: subsets vary in y extent!!!!!!!!!!!!!!") print('') return res
in_path2 = os.path.join(data_dir2, '5158', 'points_convexhull.shp') in_path3 = os.path.join(data_dir2, '3892', 'points_convexhull.shp') ## rural in_path4 = os.path.join(data_dir2, '3897', 'points_convexhull.shp') in_path5 = os.path.join(data_dir2, '4846', 'points_convexhull.shp') in_path6 = os.path.join(data_dir2, '3896', 'points_convexhull.shp') convexhulls = [] convexhulls = [in_path, in_path2, in_path3, in_path4, in_path5, in_path6] # open the raster and read out the data in a numpy array rast_data_source = gdal.Open(in_fn) # To translate coordinates to raster indices gt = rast_data_source.GetGeoTransform() inv_gt = gdal.InvGeoTransform(gt) # Get the correct driver for the gps track driver = ogr.GetDriverByName('ESRI Shapefile') index = 0 for i in convexhulls: # 0 means read-only. 1 means writeable. vect_data_source = driver.Open(i, 0) # Get the Layer class object layer = vect_data_source.GetLayer(0) # Determine the spatial extent of the track # is a list with x_left, x_right, y_bottom, y_top extent = layer.GetExtent() print('vector extent is', extent)
def __init__(self, controller): # Load map for display/GPS conversions dataset = gdal.Open(MAP_FILE) data = dataset.ReadAsArray() self.geo_trans = dataset.GetGeoTransform() self.inv_trans = gdal.InvGeoTransform(self.geo_trans) # Control parameters self.robot_stopped = True self.quit_gui = False self.mission_wps = [] #format [(lat, lon)...] ####################################################################### # GUI SECTION ####################################################################### # Set up GUI self.controller = controller self.tk = Tk() self.tk.report_callback_exception = handle_exception self.tk.title("ASV Control Interface") self.tk.protocol("WM_DELETE_WINDOW", self.on_quit) # GUI marker variables (labels on map) # Go to location self.goto_coords = (-1, -1) #UTM! #TODO: CURRENTLY NOT CHANGED self.location_select_mode = False self.cur_pos_marker = None self.target_pos_marker = None # Mission planning self.add_wps_mode = False self.remove_wps_mode = False self.running_mission_mode = False self.transect_mode = False # self.repeat_mission_mode = False self.set_border_mode = False self.wp_markers = [] self.wp_labels = [] self.border_markers = [] # Origin setting self.origin_coords = (0, 0) #pixel coords x, y = gdal.ApplyGeoTransform(self.geo_trans, 0, 0) print('Origin UTM:', x, y) self.set_origin_mode = False # Frames: Sidebar + Map Area self.sidebar_frame = Frame(self.tk, width=500, relief='sunken', borderwidth=2) self.map_frame = Frame(self.tk) self.sidebar_frame.pack(expand=True, fill='both', side='left', anchor='nw') self.map_frame.pack(expand=True, fill='both', side='right') ####################################################################### # SIDEBAR FRAME ####################################################################### # GPS Coordinates self.gps_title = Label(self.sidebar_frame, anchor='w', text='ASV GPS Information', font='Helvetica 14 bold').pack() self.gps = Label(self.sidebar_frame, anchor='w', width=30, text='Latitude: ???\nLongitude: ???\nHeading: ???') self.gps_local = Label(self.sidebar_frame, anchor='w', width=30, text='x: ???, y: ???') self.gps.pack() #self.gps_local.pack() # ADCP Data self.adcp_title = Label(self.sidebar_frame, anchor='w', text='ADCP Information', font='Helvetica 14 bold').pack() self.adcp_data = Label(self.sidebar_frame, anchor='w', width=30, text='Water depth: ???\nCurrent speed: ???') self.adcp_data.pack() # ASV Control Panel self.control_title = Label(self.sidebar_frame, anchor='w', text='ASV Control Panel', font='Helvetica 14 bold').pack() # 1) Go to map location # self.control_wp_dxdy = Label(self.sidebar_frame, anchor='w', width=30, text='dx: ???, dy: ???') # self.control_wp_dxdy.pack() self.auv_status = Label(self.sidebar_frame, anchor='w', text='ASV Status: STOPPED', fg="red") self.auv_status.pack() self.transect_mission_label = Label(self.sidebar_frame, anchor='w', text='Transect Mission: NO', fg="red") self.transect_mission_label.pack() self.transect_mission = Button(self.sidebar_frame, anchor='w', text='Enable Transect Mission', command=self.on_toggle_transect) self.transect_mission.pack() # Repeat mission (has been commented out because not useful) # self.repeat_mission_label = Label(self.sidebar_frame, anchor='w', text='Repeat Mission: NO', fg="red") # self.repeat_mission_label.pack() # self.repeat_frame = Frame(self.sidebar_frame) # self.repeat_frame.pack() # self.repeat_label = Label(self.repeat_frame, anchor='w', text='# Repeats').pack(side='left') # self.repeat_times = Entry(self.repeat_frame, width=5) # self.repeat_times.insert(END, '10') # self.repeat_times.pack(side='right') # self.repeat_mission = Button(self.sidebar_frame, anchor='w', text='Enable Repeat Mission', command=self.on_toggle_repeat_mission) # self.repeat_mission.pack() self.start_frame = Frame(self.sidebar_frame) self.start_frame.pack() self.start_stop = Button(self.start_frame, anchor='w', text='Start ASV', command=self.on_startstop) self.start_stop.pack(side='left') self.mission = Button(self.start_frame, anchor='w', text='Start Mission', command=self.on_toggle_mission) self.mission.pack(side='right') # 2) Mission planning self.mission_title = Label(self.sidebar_frame, anchor='w', text='Mission Planning', font='Helvetica 14 bold').pack() self.mission_disclaimer = Label( self.sidebar_frame, anchor='w', text= 'Red=Point Tracking(1), Orange=Transect(2).\nClick on WP in map to change color.', font='Helvetica 10 italic').pack() self.mission_frame = Frame(self.sidebar_frame) self.scrollbar = Scrollbar(self.mission_frame) self.scrollbar.pack(side='right') self.w_name = Label(self.mission_frame, text='') self.wp_list = Listbox(self.mission_frame, width=30, height=12, yscrollcommand=self.scrollbar.set) self.wp_list.pack(side='left') self.wp_list.bind('<<ListboxSelect>>', self.on_waypoint_selection) self.scrollbar.config(command=self.wp_list.yview) self.mission_frame.pack() self.mission_file_frame = Frame(self.sidebar_frame) self.mission_file_frame.pack() self.load_mission = Button( self.mission_file_frame, anchor='w', text='Load Mission File', command=self.on_load_mission).pack(side='left') self.save_mission = Button( self.mission_file_frame, anchor='w', text='Save Mission to File', command=self.on_save_mission).pack(side='right') self.mission_add_wps = Button(self.sidebar_frame, anchor='w', text='Add Waypoints', command=self.on_toggle_add_wps) self.mission_add_wps.pack() self.mission_remove_wps = Button(self.sidebar_frame, anchor='w', text='Remove Waypoints', command=self.on_toggle_remove_wps) self.mission_remove_wps.pack() self.clear_wps = Button(self.sidebar_frame, anchor='w', text='Clear All Waypoints', command=self.on_clear_wps) self.clear_wps.pack() ####################################################################### # MAP CANVAS ####################################################################### # Load map image pilImg = Image.open(MAP_FILE) pilImg = pilImg.resize((MAP_WIDTH, MAP_HEIGHT), Image.ANTIALIAS) self.img = ImageTk.PhotoImage(pilImg) # map self.canvas = Canvas(self.map_frame, width=MAP_WIDTH, height=MAP_HEIGHT) self.canvas.create_image(0, 0, image=self.img, anchor=NW) self.canvas.pack(side='top') self.canvas.bind("<Button 1>", self.on_location_click) self.origin_marker1 = self.canvas.create_line( 0, -10, 0, 10, fill='black', width=2) #to create a cross self.origin_marker2 = self.canvas.create_line(-10, 0, 10, 0, fill='black', width=2) ####################################################################### # CONFIGURATION FRAME ####################################################################### self.control_config_frame = Frame(self.map_frame, height=15) self.control_config_frame.pack(side='left') self.misc_frame = Frame(self.map_frame) self.misc_frame.pack(side='right') self.border_frame = Frame(self.misc_frame, height=15) self.border_frame.pack(side='top') self.compass_frame = Frame(self.misc_frame, height=15) self.compass_frame.pack(side='bottom') # Tracing border self.border_label = Label(self.border_frame, anchor='w', text='Border Configuration', font='Helvetica 14 bold').pack() self.border = Button(self.border_frame, anchor='w', text='Trace Border', command=self.on_toggle_border) self.border.pack() self.clear_border = Button(self.border_frame, anchor='w', text='Clear Border', command=self.on_clear_border).pack() self.load_border = Button(self.border_frame, anchor='w', text='Load Border', command=self.on_load_border).pack() self.save_border = Button(self.border_frame, anchor='w', text='Save Border', command=self.on_save_border).pack() # Compass calibration self.compass_label = Label(self.compass_frame, anchor='w', text='Compass Calibration', font='Helvetica 14 bold').pack() self.heading_frame = Frame(self.compass_frame) self.heading_frame.pack() self.heading_offset_label = Label( self.heading_frame, anchor='w', text='Heading Offset (deg)').pack(side='left') self.heading_offset = Entry(self.heading_frame, width=6) self.heading_offset.insert(END, '-12') self.heading_offset.pack(side='right') self.set_heading_offset = Button( self.compass_frame, anchor='w', text='Set Heading Offset', command=self.on_set_heading_offset).pack() # Control parameters/speed self.control_config = Label(self.control_config_frame, anchor='w', text='Control', font='Helvetica 14 bold').pack() self.control_info = Label(self.control_config_frame, anchor='w', text='ASV Speed: ?\n Speed to Dest: ?\n', fg="red") self.control_info.pack() # self.origin = Button(self.sidebar_frame, anchor='w', text='Set Map Origin', command=self.on_toggle_set_origin) # self.origin.pack() self.speed_frame = Frame(self.control_config_frame) self.speed_frame.pack() # self.set_desired_speed = Button(self.speed_frame, anchor='w', text='Set Desired Speed', command=self.on_set_desired_speed) # self.set_desired_speed.pack() # self.desired_speed_label = Label(self.speed_frame, anchor='w', text='Desired Speed (m/s)').pack(side='left') # self.desired_speed = Entry(self.speed_frame, width=10) # self.desired_speed.insert(END, '3') # self.desired_speed.bind('<Return>', self.on_set_desired_speed) # self.desired_speed.pack(side='right') ####################################################################### # Point Tracking Parameters ####################################################################### self.Kp_frame = Frame(self.control_config_frame) self.Kp_frame.pack() self.Kp_ang_label = Label(self.Kp_frame, anchor='w', text='K_ang').pack(side='left') self.Kp_ang = Entry(self.Kp_frame, width=5) self.Kp_ang.insert(END, '800') self.Kp_ang.pack(side='left') self.Kp_nom_label = Label(self.Kp_frame, anchor='w', text='K_nom').pack(side='left') self.Kp_nom = Entry(self.Kp_frame, width=5) self.Kp_nom.insert(END, '1000') self.Kp_nom.pack(side='left') self.K_vi_label = Label(self.Kp_frame, anchor='w', text='K_vi').pack(side='left') self.K_vi = Entry(self.Kp_frame, width=5) self.K_vi.insert(END, '0') self.K_vi.pack(side='left') ####################################################################### # Transect Parameters ####################################################################### self.transect_frame1 = Frame(self.control_config_frame) self.transect_frame1.pack() self.K_v_label = Label(self.transect_frame1, anchor='w', text='K_v').pack(side='left') self.K_v = Entry(self.transect_frame1, width=5) self.K_v.insert(END, '0.5') self.K_v.pack(side='left') self.K_latAng_label = Label(self.transect_frame1, anchor='w', text='K_latAng').pack(side='left') self.K_latAng = Entry(self.transect_frame1, width=5) self.K_latAng.insert(END, '0.5') self.K_latAng.pack(side='left') self.K_vert_label = Label(self.transect_frame1, anchor='w', text='K_vert').pack(side='left') self.K_vert = Entry(self.transect_frame1, width=5) self.K_vert.insert(END, '1000') self.K_vert.pack(side='left') self.transect_frame2 = Frame(self.control_config_frame) self.transect_frame2.pack() self.v_rate_label = Label(self.transect_frame2, anchor='w', text='v_rate').pack(side='left') self.v_rate = Entry(self.transect_frame2, width=5) self.v_rate.insert(END, '5') self.v_rate.pack(side='left') self.a_rate_label = Label(self.transect_frame2, anchor='w', text='a_rate').pack(side='left') self.a_rate = Entry(self.transect_frame2, width=5) self.a_rate.insert(END, '5') self.a_rate.pack(side='left') self.vx_des_label = Label(self.transect_frame2, anchor='w', text='vx_des').pack(side='left') self.vx_des = Entry(self.transect_frame2, width=5) self.vx_des.insert(END, '1') self.vx_des.pack(side='left') ####################################################################### # Throttle Thresholds ####################################################################### self.throttle_frame = Frame(self.control_config_frame) self.throttle_frame.pack() self.fwd_limit_frame = Frame(self.throttle_frame) self.fwd_limit_frame.pack(side='left') self.fwd_limit_label = Label(self.fwd_limit_frame, anchor='w', text='Fwd Limit').pack(side='left') self.fwd_limit = Entry(self.fwd_limit_frame, width=5) self.fwd_limit.insert(END, '1000') self.fwd_limit.pack(side='right') self.bwd_limit_frame = Frame(self.throttle_frame) self.bwd_limit_frame.pack(side='right') self.bwd_limit_label = Label(self.bwd_limit_frame, anchor='w', text='Bwd Limit').pack(side='left') self.bwd_limit = Entry(self.bwd_limit_frame, width=5) self.bwd_limit.insert(END, '1000') self.bwd_limit.pack(side='right') self.set_control_params = Button(self.control_config_frame, anchor='w', text='Set Control Params', command=self.on_set_control).pack()
# Step 1.3: Create a path to land cover raster file in_rast = os.path.join(data_dir, 'Eurasia_Landcover.tif') # Step 1.4: Create a path to an empty raster output file out_rast = os.path.join(data_dir, 'clipped_Eurasia_Landcover.tif') ################################################## OPEN RASTER AND TRANSLATE COORDINATES TO RASTER INDICES # Step 2.1: Open the raster file rast_ds = gdal.Open(in_rast) print("Projection of Raster dataset: {}".format(rast_ds.GetProjection())) # Step 2.2: Translate coordinates to raster indices geoTrans = rast_ds.GetGeoTransform() inv_geoTrans = gdal.InvGeoTransform(geoTrans) ################################################## GET GPS TRACK DRIVER, OPEN VECTOR LAYER AND CALCULATE EXTENT # Step 3.1: Get the correct driver for the gps track vect_driver = ogr.GetDriverByName('ESRI Shapefile') # Step 3.2: Open the vector data source in Python3 and check to see if shapefile is found by the code # Note: 0 means read-only. 1 means writeable, vect_ds = ogr.Open(in_vect, 0) # Step 3.3: Check if 'vect_data_source' was opened correctly through the input vector path # Note: The term 'None' means 'if not found by the code' and the conditional statement ensures that errors won't occur if vect_ds is None: print('Could not open %s' % (in_vect)) # Step 3.4: You've loaded the vector data source, now create a layer for the contents pane with GetLayer() function