|
|
import gradio as gr |
|
|
import numpy as np |
|
|
import torch |
|
|
import matplotlib.pyplot as plt |
|
|
import cv2 |
|
|
import os |
|
|
import leafmap |
|
|
from samgeo import SamGeo, show_image, download_file, overlay_images, tms_to_geotiff |
|
|
from zipfile import ZipFile |
|
|
|
|
|
|
|
|
|
|
|
sam = SamGeo( |
|
|
model_type="vit_h", |
|
|
checkpoint='sam_vit_h_4b8939.pth', |
|
|
sam_kwargs=None, |
|
|
) |
|
|
|
|
|
def get_all_file_paths(directory): |
|
|
|
|
|
|
|
|
file_paths = [] |
|
|
|
|
|
|
|
|
for root, directories, files in os.walk(directory): |
|
|
for filename in files: |
|
|
|
|
|
filepath = os.path.join(root, filename) |
|
|
file_paths.append(filepath) |
|
|
|
|
|
|
|
|
return file_paths |
|
|
|
|
|
def get_shape_files(image): |
|
|
filename, file_extension = os.path.splitext(image.name) |
|
|
|
|
|
if file_extension in ['.tif','tiff']: |
|
|
|
|
|
storage='ShapeFiles_Folder' |
|
|
if os.path.exists(storage): |
|
|
pass |
|
|
else: |
|
|
os.mkdir(storage) |
|
|
|
|
|
zip_folder=f'{storage}/zip_folder' |
|
|
if os.path.exists(zip_folder): |
|
|
pass |
|
|
else: |
|
|
os.mkdir(zip_folder) |
|
|
|
|
|
out_file=f'{storage}/out_files' |
|
|
if os.path.exists(out_file): |
|
|
pass |
|
|
else: |
|
|
os.mkdir(out_file) |
|
|
|
|
|
|
|
|
sam.generate(image.name, output=f"{out_file}/masks.tif", foreground=True, unique=True) |
|
|
sam.tiff_to_vector(f"{out_file}/masks.tif", out_file) |
|
|
sam.show_anns(axis="off", alpha=1, output=f"{out_file}/annotations.tif") |
|
|
|
|
|
|
|
|
image = cv2.imread(f"{out_file}/annotations.tif") |
|
|
cv2.imwrite("{}/{}.jpg".format(out_file,'converted'), image) |
|
|
|
|
|
|
|
|
file_paths=get_all_file_paths(out_file) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
with ZipFile(f'{zip_folder}/shapefile.zip','w') as zip: |
|
|
|
|
|
for file in file_paths: |
|
|
zip.write(file) |
|
|
|
|
|
print('All files zipped successfully!') |
|
|
|
|
|
return f"{out_file}/converted.jpg",f'{zip_folder}/shapefile.zip' |
|
|
|
|
|
else: |
|
|
return "Try uploading .tif file for processing!." |
|
|
|
|
|
my_app = gr.Blocks() |
|
|
with my_app: |
|
|
gr.Markdown("<center><h1>Farmland Segmentation using Satellite Image data</h1></center>") |
|
|
gr.Markdown("<center><h3>Provided with a .tif image file of satellite, this app can segment the farmlands</h></center>") |
|
|
with gr.TabItem("Get Shapefiles"): |
|
|
with gr.Row(): |
|
|
with gr.Column(): |
|
|
img_source = gr.File(label="Please select source tif") |
|
|
source_image_loader = gr.Button("Get Shape File") |
|
|
with gr.Column(): |
|
|
image=gr.Image() |
|
|
output = gr.outputs.File("zip") |
|
|
source_image_loader.click(get_shape_files,img_source,[image,output]) |
|
|
my_app.launch(debug = True) |