Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def get_mask_aoi_cell(vector_file, vector_layer, vector_feature, x, y, width=4000, height=4000, epsg=4326):
import gdal
import osr
driver = gdal.GetDriverByName("MEM")
assert driver
raster = driver.Create("", width, height, 1, gdal.GDT_Byte)
assert raster
raster.SetGeoTransform((x, 0.00025, 0.0, y+1, 0.0, -0.00025))
srs = osr.SpatialReference()
srs.ImportFromEPSG(epsg)
raster.SetProjection(srs.ExportToWkt())
import ogr
from gdalconst import GA_ReadOnly
vector = ogr.Open(vector_file, GA_ReadOnly)
assert vector
layer = vector.GetLayer(vector_layer)
def getGDALGDT(dt):
"""
Need arr.dtype.name in entry.
Returns gdal_dt from dt (numpy/scipy).
Parameters
----------
dt : datatype
Return
----------
gdal_dt : gdal datatype
"""
if dt == 'bool' or dt == 'uint8':
gdal_dt = gdal.GDT_Byte
elif dt == 'int8' or dt == 'int16':
gdal_dt = gdal.GDT_Int16
elif dt == 'uint16':
gdal_dt = gdal.GDT_UInt16
elif dt == 'int32':
gdal_dt = gdal.GDT_Int32
elif dt == 'uint32':
gdal_dt = gdal.GDT_UInt32
elif dt == 'int64' or dt == 'uint64' or dt == 'float16' or dt == 'float32':
gdal_dt = gdal.GDT_Float32
elif dt == 'float64':
gdal_dt = gdal.GDT_Float64
elif dt == 'complex64':
gdal_dt = gdal.GDT_CFloat64
else:
print('Data type non-suported')
if args.debug:
cv2.imshow('mask', good_mask.astype(numpy.uint8)*255)
cv2.waitKey(0)
cv2.destroyAllWindows()
# convert the mask to label map with value 2 (background),
# 6 (building), and 17 (elevated roadway)
cls = numpy.full(good_mask.shape, 2)
cls[good_mask] = 6
if use_roads:
cls[road_bridges] = 17
# create the mask image
print("Create destination mask of size:({}, {}) ..."
.format(dsm_file.RasterXSize, dsm_file.RasterYSize))
gdal_save(cls, dsm_file, args.destination_mask, gdal.GDT_Byte,
options=['COMPRESS=DEFLATE'])
def gdalfill_b(b, edgemask=True, prog_func=None):
# Create mask of exterior nodata
bma = iolib.b_getma(b)
# Check to make sure there are actually holes
# if bma.count_masked() > 0:
if np.any(bma.mask):
# Create 8-bit mask_ds, and add edgemask
mask_ds = memdrv.Create('', b.XSize, b.YSize, 1, gdal.GDT_Byte)
maskband = mask_ds.GetRasterBand(1)
# The - here inverts the mask so that holes are set to 0 (invalid) and
# filled by gdalFillNodata
maskband.WriteArray((-bma.mask).astype(int))
# Now fill holes in the output
print("Filling holes")
max_distance = 40
smoothing_iterations = 0
fill_opt = []
gdal.FillNodata(b, maskband, max_distance,
smoothing_iterations, fill_opt, callback=prog_func)
# Apply the original edgemask
# Note: need to implement convexhull option like geolib.get_outline
if edgemask:
print("Create destination image (height is {}), "
"size:({}, {}) ...".format("float32" if not args.type else args.type,
sourceImage.RasterXSize,
sourceImage.RasterYSize))
# georeference information
projection = sourceImage.GetProjection()
transform = sourceImage.GetGeoTransform()
gcpProjection = sourceImage.GetGCPProjection()
gcps = sourceImage.GetGCPs()
options = []
# ensure that space will be reserved for geographic corner coordinates
# (in DMS) to be set later
if (driver.ShortName == "NITF" and not projection):
options.append("ICORDS=G")
if (args.type == "uint8"):
eType = gdal.GDT_Byte
dtype = numpy.uint8
MAX_VALUE = 255
elif (args.type == "uint16"):
eType = gdal.GDT_UInt16
dtype = numpy.uint16
MAX_VALUE = 65535
else:
eType = gdal.GDT_Float32
dtype = numpy.float32
destImage = driver.Create(
args.destination_image, xsize=sourceImage.RasterXSize,
ysize=sourceImage.RasterYSize, bands=1, eType=eType,
options=options)
if (projection):
# georeference through affine geotransform
destImage.SetProjection(projection)
def save_output(img, out_path):
img = img.astype(int)
driver = gdal.GetDriverByName('GTiff')
out_dataset = driver.Create(out_path,
img.shape[1],
img.shape[0],
1,
gdal.GDT_Byte)
out_dataset.GetRasterBand(1).WriteArray(img)
out_dataset = None
Image.fromarray(ColorImage(img).astype(
'uint8')).save(out_path + '_color.png')
for i in range(S):
index = np.where(ori_img==i)
tmp[index]=histM[i]
# plt.imshow(tmp)
# plt.show()
result.append(tmp)
outputfile = os.path.join(output_dir, absname)
driver = gdal.GetDriverByName("GTiff")
if '8' in result_bits:
outdataset = driver.Create(outputfile, W, H, C, gdal.GDT_Byte)
# outdataset.SetGeoTransform(geoinfo)
elif '16' in result_bits:
outdataset = driver.Create(outputfile, W, H, C, gdal.GDT_UInt16)
# outdataset.SetGeoTransform(geoinfo)
outdataset.SetGeoTransform(geoinfo)
for i in range(C):
outdataset.GetRasterBand(i + 1).WriteArray(result[i])
del outdataset
print("Result saved to:{}".format(outputfile))
gc.collect()
# type: (thelper.data.geo.parsers.SlidingWindowDataset, AnyStr, int) -> Tuple[gdal.Dataset, gdal.Dataset]
"""
Generates the ``class`` and ``probs`` datasets to be filed by inference results.
"""
logger.info("Preparing output rasters")
logger.debug("using output name: [%s]", raster_loader.raster["name"])
xsize = raster_loader.raster["xsize"]
ysize = raster_loader.raster["ysize"]
georef = raster_loader.raster["georef"]
affine = raster_loader.raster["affine"]
raster_name = raster_loader.raster["name"]
raster_class_name = f"{raster_name}_class.tif"
raster_class_path = os.path.join(output_path, raster_class_name)
# Create the class raster output
class_ds = gdal.GetDriverByName('GTiff').Create(raster_class_path, xsize, ysize, 1, gdal.GDT_Byte)
if class_ds is None:
raise IOError(f"Unable to create: [{raster_class_path}]")
else:
logger.debug(f"Creating: [{raster_class_path}]")
class_ds.SetGeoTransform(affine)
class_ds.SetProjection(georef)
class_band = class_ds.GetRasterBand(1)
class_band.SetNoDataValue(0)
class_ds.FlushCache() # save to disk
class_ds = None # noqa # need to close before open-update
class_band = None # noqa # also close band (remove ptr)
class_ds = gdal.Open(raster_class_path, gdal.GA_Update)
# Create the probabilities raster output
raster_prob_name = f"{raster_name}_probs.tif"
raster_prob_path = os.path.join(output_path, raster_prob_name)
probs_ds = gdal.GetDriverByName('GTiff').Create(raster_prob_path, xsize, ysize, class_count, gdal.GDT_Float32)
pointsX.append(lon)
pointsY.append(lat)
xmin = min(pointsX)
xmax = max(pointsX)
ymin = min(pointsY)
ymax = max(pointsY)
# Specify offset and rows and columns to read
xoff = int((xmin - xOrigin)/pixelWidth)
yoff = int((yOrigin - ymax)/pixelWidth)
xcount = int((xmax - xmin)/pixelWidth)+1
ycount = int((ymax - ymin)/pixelWidth)+1
# Create memory target raster
target_ds = gdal.GetDriverByName('MEM').Create('', xcount, ycount, 1, gdal.GDT_Byte)
target_ds.SetGeoTransform((xmin, pixelWidth, 0, ymax, 0, pixelHeight))
# Create for target raster the same projection as for the value raster
raster_srs = osr.SpatialReference();
raster_srs.ImportFromWkt(raster.GetProjectionRef());
target_ds.SetProjection(raster_srs.ExportToWkt());
# Rasterize zone polygon to raster
gdal.RasterizeLayer(target_ds, [1], layer, options = ["ALL_TOUCHED=TRUE", "BURN_VALUE_FROM"]);
# Read raster as arrays
mean = [];
valor = 0
iteration = 0
bands = raster.RasterCount;
tt = tt.astype(np.uint8)
# tt = tt.astype(np.uint16)
tt[tind] = 0
out = tt.reshape((height, width))
result.append(out)
# plt.imshow(out)
# plt.show()
# cv2.imwrite((output_path + '%d.png' % i),out)
outputfile = os.path.join(output_path, absname)
driver = gdal.GetDriverByName("GTiff")
outdataset = driver.Create(outputfile, width, height, im_bands, gdal.GDT_Byte)
# outdataset = driver.Create(outputfile, width, height, im_bands, gdal.GDT_UInt16)
# if im_bands ==1:
# outdataset.GetRasterBand(1).WriteArray(result[0])
# else:
for i in range(im_bands):
# outdataset.GetRasterBand(i+1).WriteArray(result[i])
outdataset.GetRasterBand(i + 1).WriteArray(result[i])
del outdataset