Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# for new files, use this as a basic default
# FUTURE: Use Dataset name instead when we can read multi-dataset files
d[Info.DATASET_NAME] = os.path.split(source_path)[-1]
band = gtiff.GetRasterBand(1)
d[Info.SHAPE] = rows, cols = (band.YSize, band.XSize)
# Fix PROJ4 string if it needs an "+over" parameter
p = Proj(d[Info.PROJ])
lon_l, lat_u = p(ox, oy, inverse=True)
lon_r, lat_b = p(ox + cw * cols, oy + ch * rows, inverse=True)
if "+over" not in d[Info.PROJ] and lon_r < lon_l:
LOG.debug("Add '+over' to geotiff PROJ.4 because it seems to cross the anti-meridian")
d[Info.PROJ] += " +over"
bandtype = gdal.GetDataTypeName(band.DataType)
if bandtype.lower() != 'float32':
LOG.warning('attempting to read geotiff files with non-float32 content')
gtiff_meta = GeoTiffImporter._check_geotiff_metadata(gtiff)
d.update(gtiff_meta)
generate_guidebook_metadata(d)
LOG.debug("GeoTIFF metadata for {}: {}".format(source_path, repr(d)))
return d
################################################################
# set up output file
################################################################
# open output file exists
# remove existing file and regenerate
if os.path.isfile(raster_output):
os.remove(raster_output)
# create a new file
logger.debug("Generating output file %s" % (raster_output))
# find data type to use
if not output_type:
# use the largest type of the input files
output_type = gdal.GetDataTypeName(max(datatype_nums))
# create file
output_driver = gdal.GetDriverByName('MEM')
output_dataset = output_driver.Create(
'', dimensions[0], dimensions[1], allbandscount,
gdal.GetDataTypeByName(output_type))
# set output geo info based on first input layer
output_dataset.SetGeoTransform(gdal_get_transform(datasets[0]))
output_dataset.SetProjection(gdal_get_projection(datasets[0]))
if nodata is None:
nodata = ndv_lookup[output_type]
for i in range(1, allbandscount+1):
output_band = output_dataset.GetRasterBand(i)
else:
raise RuntimeError("Error: unknown RGB channels in {}-band "
"image".format(num_bands))
print("Assuming RGB labels on bands {}".format(rgb_bands))
else:
print("Found RGB labels on bands {}".format(rgb_bands))
# Set the output data type, either match the input or use byte (uint8)
if args.byte:
eType = gdal.GDT_Byte
else:
eType = msi_image.GetRasterBand(1).DataType
# Create the output RGB image
print("Create destination image (format {}), "
"size:({}, {}) ...".format(gdal.GetDataTypeName(eType),
msi_image.RasterXSize,
msi_image.RasterYSize))
projection = msi_image.GetProjection()
transform = msi_image.GetGeoTransform()
gcpProjection = msi_image.GetGCPProjection()
gcps = msi_image.GetGCPs()
options = ["PHOTOMETRIC=RGB", "COMPRESS=DEFLATE"]
if (args.big):
options.append("BIGTIFF=YES")
else:
options.append("BIGTIFF=IF_SAFER")
num_out_bands = 3
if args.alpha:
options.append("ALPHA=YES")
num_out_bands = 4
# ensure that space will be reserved for geographic corner coordinates
self.ulx = self.geotransform[0]
self.uly = self.geotransform[3]
self.lrx = self.ulx + self.geotransform[1] * self.xsize
self.lry = self.uly + self.geotransform[5] * self.ysize
self.band_types = [None]
self.nodata = [None]
self.cts = [None]
self.color_interps = [None]
for i in range(1, fh.RasterCount+1):
band = fh.GetRasterBand(i)
self.band_types.append(band.DataType)
if band.GetNoDataValue() != None:
self.nodata.append(band.GetNoDataValue())
self.color_interps.append(band.GetRasterColorInterpretation())
self.datatypename = gdal.GetDataTypeName(band.DataType)
self.blocksizex, self.blocksizey = band.GetBlockSize()
ct = band.GetRasterColorTable()
if ct is not None:
self.cts.append(ct.Clone())
self.palette = True
else:
self.palette = False
self.cts.append(None)
return True
# Geographic transform & projection
self.geo_transform = ds.GetGeoTransform()
self.projection = ds.GetProjection()
# File type and format
self.fformat = ds.GetDriver().ShortName
if self.fformat == 'ENVI':
interleave = ds.GetMetadata('IMAGE_STRUCTURE')['INTERLEAVE']
if interleave == 'PIXEL':
self.fformat = 'BIP'
elif interleave == 'BAND':
self.fformat = 'BSQ'
# Data type
self.datatype = gdal.GetDataTypeName(ds.GetRasterBand(1).DataType)
if self.datatype == 'Byte':
self.datatype = 'uint8'
self.datatype = np.dtype(self.datatype)
# Band names
self.band_names = []
for i in range(ds.RasterCount):
band = ds.GetRasterBand(i + 1)
if (band.GetDescription() is not None and
len(band.GetDescription()) > 0):
self.band_names.append(band.GetDescription())
else:
self.band_names.append('Band %s' % str(i + 1))
ds = None
(object) --> dict
Return: meta info of cells in raster
"""
raster_dataset = gdal.Open(raster_file_name, GA_ReadOnly)
# get cell size info
if raster_dataset:
rows = raster_dataset.RasterYSize
columns = raster_dataset.RasterXSize
proj_wkt = raster_dataset.GetProjection()
cell_size_x_value = raster_dataset.GetGeoTransform()[1] if proj_wkt else 0
cell_size_y_value = abs(raster_dataset.GetGeoTransform()[5]) if proj_wkt else 0
band = raster_dataset.GetRasterBand(1)
cell_data_type = gdal.GetDataTypeName(band.DataType)
cell_info = OrderedDict([
('rows', rows),
('columns', columns),
('cellSizeXValue', cell_size_x_value),
('cellSizeYValue', cell_size_y_value),
('cellDataType', cell_data_type),
])
else:
cell_info = OrderedDict([
('rows', None),
('columns', None),
('cellSizeXValue', None),
('cellSizeYValue', None),
('cellDataType', None),
################################################################
# set up output file
################################################################
# open output file exists
# remove existing file and regenerate
if os.path.isfile(raster_output):
os.remove(raster_output)
# create a new file
logger.debug("Generating output file %s" % (raster_output))
# find data type to use
if not output_type:
# use the largest type of the input files
output_type = gdal.GetDataTypeName(max(datatype_nums))
# create file
output_driver = gdal.GetDriverByName('MEM')
output_dataset = output_driver.Create(
'', dimensions[0], dimensions[1], allbandscount,
gdal.GetDataTypeByName(output_type))
# set output geo info based on first input layer
output_dataset.SetGeoTransform(datasets[0].GetGeoTransform())
output_dataset.SetProjection(datasets[0].GetProjection())
if nodata is None:
nodata = ndv_lookup[output_type]
for i in range(1, allbandscount+1):
output_band = output_dataset.GetRasterBand(i)
if checkOption('PCRaster'):
pcraster.setclone(maskmapAttr['row'], maskmapAttr['col'], maskmapAttr['cell'], maskmapAttr['x'], maskmapAttr['y'])
#map = numpy2pcr(Boolean, mapnp, 0)
flagmap = True
except:
# load geotiff
try:
filename = cbinding(name)
nf2 = gdal.Open(filename, GA_ReadOnly)
geotransform = nf2.GetGeoTransform()
setmaskmapAttr( geotransform[0], geotransform[3], nf2.RasterXSize, nf2.RasterYSize, geotransform[1])
band = nf2.GetRasterBand(1)
bandtype = gdal.GetDataTypeName(band.DataType)
mapnp = band.ReadAsArray(0, 0, nf2.RasterXSize, nf2.RasterYSize)
mapnp[mapnp > 1] = 0
if checkOption('PCRaster'):
pcraster.setclone(maskmapAttr['row'], maskmapAttr['col'], maskmapAttr['cell'], maskmapAttr['x'], maskmapAttr['y'])
#map = numpy2pcr(Boolean, mapnp, 0)
flagmap = True
except:
raise CWATMFileError(filename, sname=name)
if Flags['check']:
checkmap(name, filename, mapnp, flagmap, 0)