Last active
September 24, 2020 12:46
-
-
Save Samshal/892445e23caf6e477b40cb3c37891a1d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# coding: utf-8 | |
# This calculates the area of a raster by summing the squares | |
# of all pixel grids and grouping similar grids based on their rgb value | |
import rasterio | |
import os, sys | |
import matplotlib.pyplot as plt | |
import numpy as np | |
from PIL import Image | |
from osgeo import gdal | |
import urllib.request | |
colors = { | |
"157,198,116,255":"light_green", | |
"235,237,140,255":"yellow", | |
"86,160,92,255":"dark_green", | |
"135,206,250,255":"blue" | |
} | |
def get_pixel_area(geo_file): | |
with rasterio.open(geo_file) as raster: | |
pixel_area = raster.res[0]*raster.res[1] | |
return pixel_area | |
def get_color_distribution(raster_file): | |
data = Image.open(raster_file) | |
pixel_values = list(data.getdata()) | |
all_colors = {} | |
for rgba in pixel_values: | |
if ((0, 0, 0, 0) != rgba): | |
key = ",".join([str(i) for i in rgba]) | |
if key in all_colors: | |
all_colors[key] += 1 | |
else: | |
all_colors[key] = 1 | |
return all_colors | |
def calculate_areas(pixel_area, distribution): | |
area_sum = 0 | |
areas = {} | |
for color in colors.items(): | |
areas[color[1]] = 0 | |
for item in distribution.items(): | |
area = item[1] * pixel_area | |
area_sum += area | |
areas[colors[item[0]]] = area | |
return {"area_sum":area_sum, "areas":areas} | |
from flask import * | |
api = Flask(__name__) | |
@api.route('/get-area', methods=['GET', 'POST']) | |
def success(): | |
if request.method == 'POST': | |
tif_name = "last.tif" | |
save_path="./"+tif_name | |
# print(request.files) | |
tif = request.form["url"] | |
# tif.save(save_path) | |
else: | |
tif = request.args.get("url") | |
data = urllib.request.urlretrieve(tif) | |
_tif = data[0] | |
data_path_png = "./ras.png" | |
data_path_tif = "./geo.tiff" | |
gdal.Warp(data_path_tif, _tif, dstSRS="EPSG:3857") | |
gdal.Translate(data_path_png, _tif) | |
px_a = get_pixel_area(data_path_tif) | |
col_dst = get_color_distribution(data_path_png) | |
res = calculate_areas(px_a, col_dst) | |
return {"status":1, "result":res} | |
if __name__ == '__main__': | |
api.run(host="0.0.0.0") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment