def get_stats(self, file_path, remove_file=False): s = rasterstats.get_raster_statistics(file_path, True) hist = rasterstats.get_histogram(file_path, True) stats = {"stats": s,"hist": hist} # remove tmp file if ( remove_file is True): filesystem.remove(file_path) return stats
def get_zonalstatics_by_json(input_raster, json, force=True, dstnodata="nodata"): print json print "------------- " json_file = filesystem.create_tmp_file(json, "json_", ".json") shp_file = vector.create_shapefile_from_json(json_file) shp = ogr.Open(shp_file) lyr = shp.GetLayer() stats = [] # loop through the features in the layer feature = lyr.GetNextFeature() # print feature i = 0 while feature: # create a tmp shapefile feature_shp_file = vector.create_shp_from_feature(feature) # create a tmp raster raster_file = crop_raster_by_vector(input_raster, feature_shp_file, dstnodata) # do statistics on the new raster stat = get_raster_statistics(raster_file, force) # calculate histogram hist = get_histogram(raster_file, force) stats.append({"fid": i, "stat": stat, "hist": hist}) # check next feature feature = lyr.GetNextFeature() i += 1 # remove tmp raster file filesystem.remove(raster_file) # TODO: how remove all files related to the shp? # filesystem.remove(feature_shp_file.replace(".shp", ".*")) # remove tmp json and shp files filesystem.remove(json_file) filesystem.remove(shp_file) return stats