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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import folium
|
| 3 |
+
from streamlit_folium import folium_static
|
| 4 |
+
import requests
|
| 5 |
+
import tempfile
|
| 6 |
+
import os
|
| 7 |
+
import shutil
|
| 8 |
+
import zipfile
|
| 9 |
+
from PIL import Image
|
| 10 |
+
import numpy as np
|
| 11 |
+
import io
|
| 12 |
+
import gdown
|
| 13 |
+
import pandas as pd
|
| 14 |
+
import time
|
| 15 |
+
from folium import plugins
|
| 16 |
+
from huggingface_hub import hf_hub_download
|
| 17 |
+
from ultralytics.utils.plotting import Annotator
|
| 18 |
+
import torch
|
| 19 |
+
import torch.nn as nn
|
| 20 |
+
from ultralytics import YOLO
|
| 21 |
+
import tensorflow as tf
|
| 22 |
+
import matplotlib
|
| 23 |
+
from tensorflow import keras
|
| 24 |
+
from tensorflow.keras.preprocessing.image import img_to_array, array_to_img
|
| 25 |
+
import matplotlib.pyplot as plt
|
| 26 |
+
import simplekml
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
st.set_page_config(layout="wide")
|
| 30 |
+
|
| 31 |
+
# url = 'https://drive.google.com/uc?id=1DBl_LcIC3-a09bgGqRPAsQsLCbl9ZPJX'
|
| 32 |
+
if 'button1' not in st.session_state:
|
| 33 |
+
st.session_state.button1=False
|
| 34 |
+
if 'zoomed_in' not in st.session_state:
|
| 35 |
+
st.session_state.zoomed_in=True
|
| 36 |
+
if 'num_bk' not in st.session_state:
|
| 37 |
+
st.session_state.num_bk = 0
|
| 38 |
+
if 'box_lat1' not in st.session_state:
|
| 39 |
+
st.session_state.box_lat1 = 26.42
|
| 40 |
+
if 'box_lon1' not in st.session_state:
|
| 41 |
+
st.session_state.box_lon1 = 79.57
|
| 42 |
+
if 'box_lat2' not in st.session_state:
|
| 43 |
+
st.session_state.box_lat2 = 26.39
|
| 44 |
+
if 'box_lon2' not in st.session_state:
|
| 45 |
+
st.session_state.box_lon2 = 79.59
|
| 46 |
+
def callback():
|
| 47 |
+
st.session_state.button1=True
|
| 48 |
+
def callback_map():
|
| 49 |
+
st.session_state.button1=False
|
| 50 |
+
st.session_state.india_map = create_map(12)
|
| 51 |
+
if 'box_lat1' not in st.session_state:
|
| 52 |
+
st.session_state.box_lat1 = 26.42
|
| 53 |
+
if 'box_lon1' not in st.session_state:
|
| 54 |
+
st.session_state.box_lon1 = 79.57
|
| 55 |
+
if 'box_lat2' not in st.session_state:
|
| 56 |
+
st.session_state.box_lat2 = 26.39
|
| 57 |
+
if 'box_lon2' not in st.session_state:
|
| 58 |
+
st.session_state.box_lon2 = 79.59
|
| 59 |
+
st.session_state.india_map.location = [(st.session_state.box_lat1+st.session_state.box_lat2)/2,(st.session_state.box_lon1+st.session_state.box_lon2)/2]
|
| 60 |
+
st.session_state.zoomed_in=True
|
| 61 |
+
st.session_state.num_bk = 0
|
| 62 |
+
plugins.MousePosition().add_to(st.session_state.india_map)
|
| 63 |
+
|
| 64 |
+
# st.write(st.session_state.box_lat1)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# @st.cache_resource(show_spinner = False)
|
| 68 |
+
# def download_model():
|
| 69 |
+
# url = 'https://drive.google.com/uc?id=17Km_2jHSixQOrq5gqOB0RoaaeQdpNEHm'
|
| 70 |
+
# output = 'weights.pt'
|
| 71 |
+
# gdown.download(url, output, quiet=True)
|
| 72 |
+
# st.write("Downloaded successfully")
|
| 73 |
+
# download_model()
|
| 74 |
+
@st.cache_resource(show_spinner=False)
|
| 75 |
+
def load_model():
|
| 76 |
+
model_path = hf_hub_download(repo_id="Vannsh/v8x-obb", filename="obb3.pt")
|
| 77 |
+
model = YOLO(model_path,task='obb')
|
| 78 |
+
# path = "/Users/vannshjani/Downloads/yolov8_weights.pt"
|
| 79 |
+
# model = YOLO(path,task='detect')
|
| 80 |
+
return model
|
| 81 |
+
|
| 82 |
+
# model = tf.keras.models.load_model('model_resnet_fine_ind.h5')
|
| 83 |
+
mapbox_token = 'pk.eyJ1IjoiYWRpdGktMTgiLCJhIjoiY2xsZ2dlcm9zMHRiMzNkcWF2MmFjZTc3biJ9.axO4l5PRwHHn2H3wEE-cEg'
|
| 84 |
+
|
| 85 |
+
def get_static_map_image(latitude, longitude, api):
|
| 86 |
+
# Replace with your Google Maps API Key
|
| 87 |
+
base_url = 'https://maps.googleapis.com/maps/api/staticmap'
|
| 88 |
+
params = {
|
| 89 |
+
'center': f'{latitude},{longitude}',
|
| 90 |
+
'zoom': 16, # You can adjust the zoom level as per your requirement
|
| 91 |
+
'size': '640x640', # You can adjust the size of the image as per your requirement
|
| 92 |
+
'maptype': 'satellite',
|
| 93 |
+
'key': api,
|
| 94 |
+
'scale': 2,
|
| 95 |
+
}
|
| 96 |
+
response = requests.get(base_url, params=params)
|
| 97 |
+
return response.content
|
| 98 |
+
|
| 99 |
+
def create_map(zoom_level,location = [20.5937, 78.9629]):
|
| 100 |
+
india_map = folium.Map(
|
| 101 |
+
location=location,
|
| 102 |
+
# location = [26.4,79.58],
|
| 103 |
+
zoom_start=zoom_level,
|
| 104 |
+
control_scale=True,
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
# Add Mapbox tiles with 'Mapbox Satellite' style
|
| 108 |
+
folium.TileLayer(
|
| 109 |
+
tiles=f"https://api.mapbox.com/styles/v1/mapbox/satellite-streets-v12/tiles/{{z}}/{{x}}/{{y}}?access_token={mapbox_token}",
|
| 110 |
+
attr="Mapbox Satellite",
|
| 111 |
+
name="Mapbox Satellite"
|
| 112 |
+
).add_to(india_map)
|
| 113 |
+
|
| 114 |
+
plugins.MousePosition().add_to(india_map)
|
| 115 |
+
|
| 116 |
+
return india_map
|
| 117 |
+
|
| 118 |
+
def add_locations(lat,lon,india_map):
|
| 119 |
+
india_map.location = [lat, lon]
|
| 120 |
+
|
| 121 |
+
# Add marker for selected latitude and longitude
|
| 122 |
+
folium.Marker(
|
| 123 |
+
location=[lat, lon],
|
| 124 |
+
popup=f"Latitude: {lat}, Longitude: {lon}",
|
| 125 |
+
icon=folium.Icon(color='blue')
|
| 126 |
+
).add_to(india_map)
|
| 127 |
+
|
| 128 |
+
def generate_kml_content(longs, lats):
|
| 129 |
+
kml = simplekml.Kml()
|
| 130 |
+
for lon, lat in zip(longs, lats):
|
| 131 |
+
kml.newpoint(name="Brick-kiln", coords=[(lon, lat)])
|
| 132 |
+
return kml.kml()
|
| 133 |
+
def project(lat,long):
|
| 134 |
+
lat = np.radians(lat)
|
| 135 |
+
long = np.radians(long)
|
| 136 |
+
x = (128/np.pi)*(2**17)*(long + np.pi)
|
| 137 |
+
y = (128/np.pi)*(2**17)*(np.pi - np.log(np.tan(np.pi/4 + lat/2)))
|
| 138 |
+
return x,y
|
| 139 |
+
def inverse_project(x,y):
|
| 140 |
+
F = 128 / np.pi * 2 ** 17
|
| 141 |
+
lng = (x / F) - np.pi
|
| 142 |
+
lat = (2 * np.arctan(np.exp(np.pi - y/F)) - np.pi / 2)
|
| 143 |
+
lng = lng * 180 / np.pi
|
| 144 |
+
lat = lat * 180 / np.pi
|
| 145 |
+
return lat, lng
|
| 146 |
+
|
| 147 |
+
def add_box_to_map(lat1,lon1,lat2,lon2,lat3,lon3,lat4,lon4,cls,map):
|
| 148 |
+
# if cls==1:
|
| 149 |
+
# folium.Polygon([(lat1,lon1), (lat2,lon2), (lat3,lon3), (lat4,lon4)],
|
| 150 |
+
# color="blue",
|
| 151 |
+
# weight=2,
|
| 152 |
+
# fill=False,
|
| 153 |
+
# tooltip="Zigzag").add_to(st.session_state.india_map)
|
| 154 |
+
# else:
|
| 155 |
+
# folium.Polygon([(lat1,lon1), (lat2,lon2), (lat3,lon3), (lat4,lon4)],
|
| 156 |
+
# color="red",
|
| 157 |
+
# weight=2,
|
| 158 |
+
# fill=False,
|
| 159 |
+
# tooltip="FCBK").add_to(st.session_state.india_map)
|
| 160 |
+
tooltip_text = "Zigzag" if cls == 1 else "FCBK"
|
| 161 |
+
color = "blue" if cls == 1 else "red"
|
| 162 |
+
|
| 163 |
+
folium.Polygon(
|
| 164 |
+
locations=[(lat1, lon1), (lat2, lon2), (lat3, lon3), (lat4, lon4)],
|
| 165 |
+
color=color,
|
| 166 |
+
weight=2,
|
| 167 |
+
fill=False,
|
| 168 |
+
fill_opacity=0,
|
| 169 |
+
tooltip=tooltip_text
|
| 170 |
+
).add_to(map)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
# def get_new_coords(lat,long,shift):
|
| 176 |
+
# x,y = project(lat,long)
|
| 177 |
+
# if shift=="left":
|
| 178 |
+
# return inverse_project(x-640,y+640)
|
| 179 |
+
# else:
|
| 180 |
+
# return inverse_project(x+640,y-640)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
# def imgs_input_fn(images):
|
| 184 |
+
# img_size = (640, 640)
|
| 185 |
+
# img_size_tensor = tf.constant(img_size, dtype=tf.int32)
|
| 186 |
+
# images = tf.convert_to_tensor(value = images)
|
| 187 |
+
# images = tf.image.resize(images, size=img_size_tensor)
|
| 188 |
+
# return images
|
| 189 |
+
|
| 190 |
+
# def make_gradcam_heatmap(img_array, model, last_conv_layer_name, pred_index=None):
|
| 191 |
+
# # First, we create a model that maps the input image to the activations
|
| 192 |
+
# # of the last conv layer as well as the output predictions
|
| 193 |
+
# grad_model = keras.models.Model(
|
| 194 |
+
# model.inputs, [model.get_layer(last_conv_layer_name).output, model.output]
|
| 195 |
+
# )
|
| 196 |
+
# # Then, we compute the gradient of the top predicted class for our input image
|
| 197 |
+
# # with respect to the activations of the last conv layer
|
| 198 |
+
# with tf.GradientTape() as tape:
|
| 199 |
+
# last_conv_layer_output, preds = grad_model(img_array)
|
| 200 |
+
# if pred_index is None:
|
| 201 |
+
# pred_index = tf.argmax(preds[0])
|
| 202 |
+
# class_channel = preds[:, pred_index]
|
| 203 |
+
|
| 204 |
+
# # This is the gradient of the output neuron (top predicted or chosen)
|
| 205 |
+
# # with regard to the output feature map of the last conv layer
|
| 206 |
+
# grads = tape.gradient(class_channel, last_conv_layer_output)
|
| 207 |
+
|
| 208 |
+
# # This is a vector where each entry is the mean intensity of the gradient
|
| 209 |
+
# # over a specific feature map channel
|
| 210 |
+
# pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))
|
| 211 |
+
|
| 212 |
+
# # We multiply each channel in the feature map array
|
| 213 |
+
# # by "how important this channel is" with regard to the top predicted class
|
| 214 |
+
# # then sum all the channels to obtain the heatmap class activation
|
| 215 |
+
# last_conv_layer_output = last_conv_layer_output[0]
|
| 216 |
+
# heatmap = last_conv_layer_output @ pooled_grads[..., tf.newaxis]
|
| 217 |
+
# heatmap = tf.squeeze(heatmap)
|
| 218 |
+
|
| 219 |
+
# # For visualization purpose, we will also normalize the heatmap between 0 & 1
|
| 220 |
+
# heatmap = tf.maximum(heatmap, 0) / tf.math.reduce_max(heatmap)
|
| 221 |
+
# return heatmap.numpy()
|
| 222 |
+
|
| 223 |
+
# def save_and_display_gradcam(img_array, heatmap, alpha=0.4):
|
| 224 |
+
# img = img_array
|
| 225 |
+
# heatmap = np.uint8(255 * heatmap)
|
| 226 |
+
# jet = matplotlib.colormaps["jet"]
|
| 227 |
+
# jet_colors = jet(np.arange(256))[:, :3]
|
| 228 |
+
# jet_heatmap = jet_colors[heatmap]
|
| 229 |
+
|
| 230 |
+
# jet_heatmap = array_to_img(jet_heatmap)
|
| 231 |
+
# jet_heatmap = jet_heatmap.resize((img.shape[1], img.shape[0]))
|
| 232 |
+
# jet_heatmap = img_to_array(jet_heatmap)
|
| 233 |
+
|
| 234 |
+
# superimposed_img = jet_heatmap * alpha + img
|
| 235 |
+
# superimposed_img = array_to_img(superimposed_img)
|
| 236 |
+
|
| 237 |
+
# return superimposed_img
|
| 238 |
+
|
| 239 |
+
def main():
|
| 240 |
+
|
| 241 |
+
hide_st_style = """
|
| 242 |
+
<style>
|
| 243 |
+
body {
|
| 244 |
+
background-color: black;
|
| 245 |
+
color: white;
|
| 246 |
+
}
|
| 247 |
+
#MainMenu {visibility: hidden;}
|
| 248 |
+
footer {visibility: hidden;}
|
| 249 |
+
header {visibility: hidden;}
|
| 250 |
+
</style>
|
| 251 |
+
"""
|
| 252 |
+
st.markdown(hide_st_style, unsafe_allow_html=True)
|
| 253 |
+
|
| 254 |
+
model = load_model()
|
| 255 |
+
|
| 256 |
+
st.title("Brick Kiln Detector")
|
| 257 |
+
st.write("This app uses a deep learning model to detect brick kilns in satellite images. The app allows you to select certain area on a map and download the images of brick kilns and non-brick kilns in that region.")
|
| 258 |
+
|
| 259 |
+
# st.header("Instructions")
|
| 260 |
+
# st.write("1. Enter the latitude and longitude of the bounding box in the sidebar.\n"
|
| 261 |
+
# "2. Click on submit and wait for the results to load.\n"
|
| 262 |
+
# "3. Download the images and CSV file using the download buttons below.")
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
# Initialize variables to store user-drawn polygons
|
| 268 |
+
drawn_polygons = []
|
| 269 |
+
|
| 270 |
+
# Specify the latitude and longitude for the rectangular bounding box
|
| 271 |
+
st.header("Bounding Box")
|
| 272 |
+
col1, col2, col3,col4 = st.columns(4)
|
| 273 |
+
prev_lat1 = st.session_state.box_lat1
|
| 274 |
+
prev_lat2 = st.session_state.box_lat2
|
| 275 |
+
prev_lon1 = st.session_state.box_lon1
|
| 276 |
+
prev_lon2 = st.session_state.box_lon2
|
| 277 |
+
with col1:
|
| 278 |
+
st.session_state.box_lat1 = st.number_input("Lat of top-left corner:", value=26.42, step=0.01,format='%f',on_change=callback_map)
|
| 279 |
+
with col2:
|
| 280 |
+
st.session_state.box_lon1 = st.number_input("Lon of top-left corner:", value=79.57, step=0.01,on_change=callback_map)
|
| 281 |
+
with col3:
|
| 282 |
+
st.session_state.box_lat2 = st.number_input("Lat of bottom-right corner:", value=26.39, step=0.01,on_change=callback_map)
|
| 283 |
+
with col4:
|
| 284 |
+
st.session_state.box_lon2 = st.number_input("Lon of bottom-right corner:", value=79.59, step=0.01,on_change=callback_map)
|
| 285 |
+
if prev_lat1 != st.session_state.box_lat1 or prev_lat2!=st.session_state.box_lat2 or prev_lon1 != st.session_state.box_lon1 or prev_lon2!=st.session_state.box_lon2:
|
| 286 |
+
callback_map()
|
| 287 |
+
area = np.abs(st.session_state.box_lat2-st.session_state.box_lat1)*np.abs(st.session_state.box_lon2-st.session_state.box_lon1)
|
| 288 |
+
area = round(area,5)
|
| 289 |
+
st.write(f"Area of the bounding box is {area} sq units.")
|
| 290 |
+
mid_lat = (st.session_state.box_lat1+st.session_state.box_lat2)/2
|
| 291 |
+
mid_lon = (st.session_state.box_lon1+st.session_state.box_lon2)/2
|
| 292 |
+
if 'india_map' not in st.session_state:
|
| 293 |
+
st.session_state.india_map = create_map(12)
|
| 294 |
+
st.session_state.india_map.location = [mid_lat,mid_lon]
|
| 295 |
+
|
| 296 |
+
if area<=0.005:
|
| 297 |
+
submit_button = st.button("Submit",on_click=callback)
|
| 298 |
+
|
| 299 |
+
# new_box_lat1,new_box_lon1 = get_new_coords(box_lat1,box_lon1,"left")
|
| 300 |
+
# new_box_lat2,new_box_lon2 = get_new_coords(box_lat2,box_lon2,"right")
|
| 301 |
+
# box_lat1 = new_box_lat1
|
| 302 |
+
# box_lon1 = new_box_lon1
|
| 303 |
+
# box_lat2 = new_box_lat2
|
| 304 |
+
# box_lon2 = new_box_lon2
|
| 305 |
+
# Add the rectangular bounding box to the map
|
| 306 |
+
bounding_box_polygon = folium.Rectangle(
|
| 307 |
+
bounds=[[st.session_state.box_lat2, st.session_state.box_lon2], [st.session_state.box_lat1, st.session_state.box_lon1]],
|
| 308 |
+
color='red',
|
| 309 |
+
fill=True,
|
| 310 |
+
fill_opacity=0,
|
| 311 |
+
)
|
| 312 |
+
bounding_box_polygon.add_to(st.session_state.india_map)
|
| 313 |
+
drawn_polygons.append(bounding_box_polygon.get_bounds())
|
| 314 |
+
|
| 315 |
+
df = pd.DataFrame(columns = ['Sr.No','Latitude', 'Longitude','Confidence'])
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
# Display the map as an image using st.image()
|
| 319 |
+
# folium_static(world_map, width=1500, height=800)
|
| 320 |
+
folium_static(st.session_state.india_map,width=1200,height=800)
|
| 321 |
+
|
| 322 |
+
ab = st.secrets["Api_key"]
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
if ab and (submit_button or st.session_state.button1):
|
| 328 |
+
@st.cache_resource(show_spinner = False)
|
| 329 |
+
def done_before(df,drawn_polygons):
|
| 330 |
+
st.session_state.ab = ab
|
| 331 |
+
image_list = []
|
| 332 |
+
latitudes = []
|
| 333 |
+
longitudes = []
|
| 334 |
+
idx = 0
|
| 335 |
+
# lat_1 = drawn_polygons[0][0][0]
|
| 336 |
+
# lon_1 = drawn_polygons[0][0][1]
|
| 337 |
+
# lat_2 = drawn_polygons[0][1][0]
|
| 338 |
+
# lon_2 = drawn_polygons[0][1][1]
|
| 339 |
+
|
| 340 |
+
delta_lat = 0.011
|
| 341 |
+
delta_lon = 0.013
|
| 342 |
+
latitude = st.session_state.box_lat2
|
| 343 |
+
longitude = st.session_state.box_lon1
|
| 344 |
+
lat_ones = []
|
| 345 |
+
lon_ones = []
|
| 346 |
+
nlat=0
|
| 347 |
+
nlong=0
|
| 348 |
+
while latitude<=st.session_state.box_lat1:
|
| 349 |
+
nlat+=1
|
| 350 |
+
latitude+=delta_lat
|
| 351 |
+
|
| 352 |
+
while longitude<=st.session_state.box_lon2:
|
| 353 |
+
nlong+=1
|
| 354 |
+
longitude+=delta_lon
|
| 355 |
+
latitude=st.session_state.box_lat2
|
| 356 |
+
longitude=st.session_state.box_lon1
|
| 357 |
+
|
| 358 |
+
progress_text = 'Please wait while we process your request...'
|
| 359 |
+
my_bar = st.progress(0, text=progress_text)
|
| 360 |
+
|
| 361 |
+
# st.write("Predictions ongoing")
|
| 362 |
+
indices_of_zeros = []
|
| 363 |
+
indices_of_ones = []
|
| 364 |
+
prob_flat_list = []
|
| 365 |
+
results = []
|
| 366 |
+
i=0
|
| 367 |
+
while round(latitude,2)<=st.session_state.box_lat1:
|
| 368 |
+
while round(longitude,2)<=st.session_state.box_lon2:
|
| 369 |
+
image_data = get_static_map_image(latitude, longitude, ab)
|
| 370 |
+
image = Image.open(io.BytesIO(image_data))
|
| 371 |
+
# st.write(latitude,longitude)
|
| 372 |
+
|
| 373 |
+
# Get the size of the image (width, height)
|
| 374 |
+
# width, height = image.size
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
# new_height = height - 20
|
| 379 |
+
|
| 380 |
+
# Define the cropping box (left, upper, right, lower)
|
| 381 |
+
# crop_box = (0, 0, width, new_height)
|
| 382 |
+
|
| 383 |
+
# Crop the image
|
| 384 |
+
# image = image.crop(crop_box)
|
| 385 |
+
|
| 386 |
+
# new_width = 224
|
| 387 |
+
# new_height = 224
|
| 388 |
+
|
| 389 |
+
# Define the resizing box (left, upper, right, lower)
|
| 390 |
+
# resize_box = (0, 0, new_width, new_height)
|
| 391 |
+
|
| 392 |
+
# Resize the image
|
| 393 |
+
# image = image.resize((new_width, new_height), Image.LANCZOS)
|
| 394 |
+
image = image.convert('RGB')
|
| 395 |
+
temp_result = model.predict(image)
|
| 396 |
+
r = temp_result[0]
|
| 397 |
+
if len(r.obb.cls)==0:
|
| 398 |
+
indices_of_zeros.append(i)
|
| 399 |
+
elif len(r.obb.cls)==1:
|
| 400 |
+
indices_of_ones.append(i)
|
| 401 |
+
prob_flat_list.append(r.obb.conf.item())
|
| 402 |
+
lat_ones.append(latitude)
|
| 403 |
+
lon_ones.append(longitude)
|
| 404 |
+
else:
|
| 405 |
+
indices_of_ones.append(i)
|
| 406 |
+
prob_flat_list.append(r.obb.conf)
|
| 407 |
+
lat_ones.append(latitude)
|
| 408 |
+
lon_ones.append(longitude)
|
| 409 |
+
i += 1
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
# image_np_array = np.array(image)
|
| 413 |
+
|
| 414 |
+
# image_np_array = np.array(image)
|
| 415 |
+
|
| 416 |
+
results.append(temp_result[0])
|
| 417 |
+
image_list.append(image)
|
| 418 |
+
latitudes.append(latitude)
|
| 419 |
+
longitudes.append(longitude)
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
if idx >1:
|
| 423 |
+
idx = 0.95
|
| 424 |
+
longitude += delta_lon
|
| 425 |
+
my_bar.progress(idx , text=progress_text)
|
| 426 |
+
idx+=(3/(4*nlat*nlong))
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
latitude += delta_lat
|
| 432 |
+
longitude = st.session_state.box_lon1
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
# images = np.stack(image_array_list, axis=0)
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
# images = imgs_input_fn(image_array_list)
|
| 440 |
+
# predictions_prob = model.predict(images)
|
| 441 |
+
# predictions = [[1 if element >= 0.5 else 0 for element in sublist] for sublist in predictions_prob]
|
| 442 |
+
|
| 443 |
+
# prob_flat_list = [element for sublist in predictions_prob for element in sublist]
|
| 444 |
+
# flat_modified_list = [element for sublist in predictions for element in sublist]
|
| 445 |
+
|
| 446 |
+
# indices_of_ones = [index for index, element in enumerate(flat_modified_list) if element == 1]
|
| 447 |
+
# indices_of_zeros = [index for index, element in enumerate(flat_modified_list) if element == 0]
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
return indices_of_ones,latitudes,longitudes,image_list,indices_of_zeros,my_bar,results,prob_flat_list,lat_ones,lon_ones
|
| 454 |
+
indices_of_ones,latitudes,longitudes,image_list,indices_of_zeros,my_bar,results,prob_flat_list,lat_ones,lon_ones=done_before(df,drawn_polygons)
|
| 455 |
+
|
| 456 |
+
# reset = st.button("Reset")
|
| 457 |
+
|
| 458 |
+
# temp_dir1 = tempfile.mkdtemp() # Create a temporary directory to store the images
|
| 459 |
+
# st.write(indices_of_ones,prob_flat_list)
|
| 460 |
+
|
| 461 |
+
# s_no =1
|
| 462 |
+
# index = 0
|
| 463 |
+
# for i in indices_of_ones:
|
| 464 |
+
# if isinstance(prob_flat_list[index], torch.Tensor):
|
| 465 |
+
# for z in range(len(prob_flat_list[index])):
|
| 466 |
+
# truncated_float = int(prob_flat_list[index][z] * 100) / 100
|
| 467 |
+
# temp_df = pd.DataFrame({'Sr.No':[s_no],'Latitude': [round(latitudes[i],2)], 'Longitude': [round(longitudes[i],2)],'Confidence':[truncated_float]})
|
| 468 |
+
# s_no+=1
|
| 469 |
+
# # Concatenate the temporary DataFrame with the main DataFrame
|
| 470 |
+
# df = pd.concat([df, temp_df], ignore_index=True)
|
| 471 |
+
# else:
|
| 472 |
+
# truncated_float = int(prob_flat_list[index] * 100) / 100
|
| 473 |
+
# temp_df = pd.DataFrame({'Sr.No':[s_no],'Latitude': [round(latitudes[i],2)], 'Longitude': [round(longitudes[i],2)],'Confidence':[truncated_float]})
|
| 474 |
+
# s_no+=1
|
| 475 |
+
# df = pd.concat([df, temp_df], ignore_index=True)
|
| 476 |
+
# index += 1
|
| 477 |
+
# Concatenate the temporary DataFrame with the main DataFrame
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
# image_filename = f'kiln_{latitudes[i]}_{longitudes[i]}.png'
|
| 481 |
+
# image_path = os.path.join(temp_dir1, image_filename)
|
| 482 |
+
|
| 483 |
+
# pil_image = image_list[i]
|
| 484 |
+
|
| 485 |
+
# pil_image.save(image_path, format='PNG')
|
| 486 |
+
# zipf.write(image_path, arcname=image_filename)
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
# temp_dir2 = tempfile.mkdtemp() # Create a temporary directory to store the images
|
| 491 |
+
|
| 492 |
+
# with zipfile.ZipFile('images_no_kiln.zip', 'w') as zipf:
|
| 493 |
+
# for i in indices_of_zeros:
|
| 494 |
+
# image_filename = f'kiln_{latitudes[i]}_{longitudes[i]}.png'
|
| 495 |
+
# image_path = os.path.join(temp_dir2, image_filename)
|
| 496 |
+
|
| 497 |
+
# pil_image = image_list[i]
|
| 498 |
+
|
| 499 |
+
# pil_image.save(image_path, format='PNG')
|
| 500 |
+
# zipf.write(image_path, arcname=image_filename)
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
mid_lat = (st.session_state.box_lat1+st.session_state.box_lat2)/2
|
| 504 |
+
mid_lon = (st.session_state.box_lon1+st.session_state.box_lon2)/2
|
| 505 |
+
reset = st.button("Reset view")
|
| 506 |
+
if reset:
|
| 507 |
+
st.session_state.india_map.location = [mid_lat,mid_lon]
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
count_ones = []
|
| 511 |
+
count_zeros = []
|
| 512 |
+
for r in results:
|
| 513 |
+
if len(r.obb.cls)==0:
|
| 514 |
+
count_ones.append(0)
|
| 515 |
+
count_zeros.append(1)
|
| 516 |
+
else:
|
| 517 |
+
count_ones.append(len(r.obb.cls))
|
| 518 |
+
count_zeros.append(0)
|
| 519 |
+
n_count_ones = sum(count_ones)
|
| 520 |
+
n_count_zeros = sum(count_zeros)
|
| 521 |
+
my_bar.progress(0.99 , text='Please wait while we process your request...')
|
| 522 |
+
time.sleep(1)
|
| 523 |
+
my_bar.empty()
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
# st.write("The number of non-brick kilns in the selected region is: ", n_count_zeros)
|
| 527 |
+
bk_lats = []
|
| 528 |
+
bk_lons = []
|
| 529 |
+
new_lats = []
|
| 530 |
+
new_lons = []
|
| 531 |
+
conf_list = []
|
| 532 |
+
conf_new = []
|
| 533 |
+
class_list = []
|
| 534 |
+
class_new = []
|
| 535 |
+
n_zig = 0
|
| 536 |
+
n_fcbk = 0
|
| 537 |
+
dictionary = {}
|
| 538 |
+
boxes_to_take = {}
|
| 539 |
+
lat_x1 = []
|
| 540 |
+
lon_y1 = []
|
| 541 |
+
lat_x2 = []
|
| 542 |
+
lon_y2 = []
|
| 543 |
+
lat_x3 = []
|
| 544 |
+
lon_y3 = []
|
| 545 |
+
lat_x4 = []
|
| 546 |
+
lon_y4 = []
|
| 547 |
+
lat_x1_new = []
|
| 548 |
+
lon_y1_new = []
|
| 549 |
+
lat_x2_new = []
|
| 550 |
+
lon_y2_new = []
|
| 551 |
+
lat_x3_new = []
|
| 552 |
+
lon_y3_new = []
|
| 553 |
+
lat_x4_new = []
|
| 554 |
+
lon_y4_new = []
|
| 555 |
+
ind = 0
|
| 556 |
+
for i in indices_of_ones:
|
| 557 |
+
r = results[i]
|
| 558 |
+
boxes = r.obb
|
| 559 |
+
boxes_to_take[i] = []
|
| 560 |
+
lat_images = []
|
| 561 |
+
lon_images = []
|
| 562 |
+
conf_images = []
|
| 563 |
+
class_images = []
|
| 564 |
+
lat1_images = []
|
| 565 |
+
lon1_images = []
|
| 566 |
+
lat2_images = []
|
| 567 |
+
lon2_images = []
|
| 568 |
+
lat3_images = []
|
| 569 |
+
lon3_images = []
|
| 570 |
+
lat4_images = []
|
| 571 |
+
lon4_images = []
|
| 572 |
+
for box in boxes:
|
| 573 |
+
# print(box.xywhr[0])
|
| 574 |
+
x_c,y_c,w,h,r = box.xywhr[0]
|
| 575 |
+
x_c = x_c.item()
|
| 576 |
+
y_c = y_c.item()
|
| 577 |
+
result = project(lat_ones[ind], lon_ones[ind])
|
| 578 |
+
delta_y = y_c - 640
|
| 579 |
+
delta_x = x_c - 640
|
| 580 |
+
lat_value,lng_value = inverse_project(result[0]+delta_x,result[1]+delta_y)
|
| 581 |
+
# st.write(box.xyxyxyxy[0][0])
|
| 582 |
+
x1_b,y1_b,x2_b,y2_b,x3_b,y3_b,x4_b,y4_b = box.xyxyxyxy[0][0][0],box.xyxyxyxy[0][0][1],box.xyxyxyxy[0][1][0],box.xyxyxyxy[0][1][1],box.xyxyxyxy[0][2][0],box.xyxyxyxy[0][2][1],box.xyxyxyxy[0][3][0],box.xyxyxyxy[0][3][1]
|
| 583 |
+
x1_b,y1_b,x2_b,y2_b,x3_b,y3_b,x4_b,y4_b = x1_b.item(),y1_b.item(),x2_b.item(),y2_b.item(),x3_b.item(),y3_b.item(),x4_b.item(),y4_b.item()
|
| 584 |
+
delta_x1 = x1_b - 640
|
| 585 |
+
delta_y1 = y1_b - 640
|
| 586 |
+
delta_x2 = x2_b - 640
|
| 587 |
+
delta_y2 = y2_b - 640
|
| 588 |
+
delta_x3 = x3_b - 640
|
| 589 |
+
delta_y3 = y3_b - 640
|
| 590 |
+
delta_x4 = x4_b - 640
|
| 591 |
+
delta_y4 = y4_b - 640
|
| 592 |
+
lat1,lon1 = inverse_project(result[0]+delta_x1,result[1]+delta_y1)
|
| 593 |
+
lat2,lon2 = inverse_project(result[0]+delta_x2,result[1]+delta_y2)
|
| 594 |
+
lat3,lon3 = inverse_project(result[0]+delta_x3,result[1]+delta_y3)
|
| 595 |
+
lat4,lon4 = inverse_project(result[0]+delta_x4,result[1]+delta_y4)
|
| 596 |
+
to_add = True
|
| 597 |
+
if len(boxes_to_take[i]) > 0:
|
| 598 |
+
for j in range(len(boxes_to_take[i])):
|
| 599 |
+
if np.abs(lat_value-lat_images[j]) < 0.0001 and np.abs(lng_value-lon_images[j]) < 0.0001:
|
| 600 |
+
to_add = False
|
| 601 |
+
if conf_images[j] < box.conf.item():
|
| 602 |
+
lat_images[j] = lat_value
|
| 603 |
+
lon_images[j] = lng_value
|
| 604 |
+
conf_images[j] = box.conf
|
| 605 |
+
class_images[j] = box.cls
|
| 606 |
+
boxes_to_take[j].append(box)
|
| 607 |
+
lat1_images[j] = lat1
|
| 608 |
+
lon1_images[j] = lon1
|
| 609 |
+
lat2_images[j] = lat2
|
| 610 |
+
lon2_images[j] = lon2
|
| 611 |
+
lat3_images[j] = lat3
|
| 612 |
+
lon3_images[j] = lon3
|
| 613 |
+
lat4_images[j] = lat4
|
| 614 |
+
lon4_images[j] = lon4
|
| 615 |
+
break
|
| 616 |
+
if to_add:
|
| 617 |
+
lat_images.append(lat_value)
|
| 618 |
+
lon_images.append(lng_value)
|
| 619 |
+
conf_images.append(box.conf)
|
| 620 |
+
class_images.append(box.cls)
|
| 621 |
+
boxes_to_take[i].append(box)
|
| 622 |
+
lat1_images.append(lat1)
|
| 623 |
+
lon1_images.append(lon1)
|
| 624 |
+
lat2_images.append(lat2)
|
| 625 |
+
lon2_images.append(lon2)
|
| 626 |
+
lat3_images.append(lat3)
|
| 627 |
+
lon3_images.append(lon3)
|
| 628 |
+
lat4_images.append(lat4)
|
| 629 |
+
lon4_images.append(lon4)
|
| 630 |
+
# st.write(i,boxes_to_take[i])
|
| 631 |
+
bk_lats.extend(lat_images)
|
| 632 |
+
bk_lons.extend(lon_images)
|
| 633 |
+
conf_list.extend(conf_images)
|
| 634 |
+
class_list.extend(class_images)
|
| 635 |
+
lat_x1.extend(lat1_images)
|
| 636 |
+
lon_y1.extend(lon1_images)
|
| 637 |
+
lat_x2.extend(lat2_images)
|
| 638 |
+
lon_y2.extend(lon2_images)
|
| 639 |
+
lat_x3.extend(lat3_images)
|
| 640 |
+
lon_y3.extend(lon3_images)
|
| 641 |
+
lat_x4.extend(lat4_images)
|
| 642 |
+
lon_y4.extend(lon4_images)
|
| 643 |
+
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
ind += 1
|
| 648 |
+
# st.write(bk_lats,bk_lons)
|
| 649 |
+
# st.write(len(bk_lats),len(bk_lons))
|
| 650 |
+
# st.write(n_count_ones)
|
| 651 |
+
n_counts_ones_mod = n_count_ones
|
| 652 |
+
for i in range(len(bk_lats)):
|
| 653 |
+
if bk_lats[i]>=st.session_state.box_lat2 and bk_lats[i]<=st.session_state.box_lat1 and bk_lons[i]>=st.session_state.box_lon1 and bk_lons[i]<=st.session_state.box_lon2:
|
| 654 |
+
new_lats.append(bk_lats[i])
|
| 655 |
+
new_lons.append(bk_lons[i])
|
| 656 |
+
conf_new.append(conf_list[i])
|
| 657 |
+
class_new.append(class_list[i])
|
| 658 |
+
lat_x1_new.append(lat_x1[i])
|
| 659 |
+
lon_y1_new.append(lon_y1[i])
|
| 660 |
+
lat_x2_new.append(lat_x2[i])
|
| 661 |
+
lon_y2_new.append(lon_y2[i])
|
| 662 |
+
lat_x3_new.append(lat_x3[i])
|
| 663 |
+
lon_y3_new.append(lon_y3[i])
|
| 664 |
+
lat_x4_new.append(lat_x4[i])
|
| 665 |
+
lon_y4_new.append(lon_y4[i])
|
| 666 |
+
continue
|
| 667 |
+
else:
|
| 668 |
+
n_counts_ones_mod -= 1
|
| 669 |
+
# st.write(n_counts_ones_mod)
|
| 670 |
+
# st.write("new")
|
| 671 |
+
# st.write(new_lats,new_lons,conf_new,class_new,boxes_to_take)
|
| 672 |
+
assert len(new_lats) == len(lat_x1_new)
|
| 673 |
+
if n_counts_ones_mod!=0:
|
| 674 |
+
|
| 675 |
+
for i in range(len(class_new)):
|
| 676 |
+
if len(class_new[i])==1:
|
| 677 |
+
if class_new[i].item()==0:
|
| 678 |
+
n_fcbk += 1
|
| 679 |
+
else:
|
| 680 |
+
n_zig += 1
|
| 681 |
+
else:
|
| 682 |
+
for j in range(len(class_new[i])):
|
| 683 |
+
if class_new[i][j].item()==0:
|
| 684 |
+
n_fcbk += 1
|
| 685 |
+
else:
|
| 686 |
+
n_zig += 1
|
| 687 |
+
|
| 688 |
+
dictionary["ZIGZAG"] = n_zig
|
| 689 |
+
dictionary["FCBK"] = n_fcbk
|
| 690 |
+
dictionary["Total"] = n_zig+n_fcbk
|
| 691 |
+
df2 = pd.DataFrame(dictionary,index=[0])
|
| 692 |
+
df2 = df2.T
|
| 693 |
+
df2.columns = ['Count']
|
| 694 |
+
# middle align df2 to be at center of page
|
| 695 |
+
st.write(":red[Red] bounding boxes represent :red[FCBK] and :blue[Blue] bounding boxes represent :blue[Zigzag].")
|
| 696 |
+
st.write(df2,use_container_width=True)
|
| 697 |
+
s_no =1
|
| 698 |
+
indexs = 0
|
| 699 |
+
# st.write(len(new_lats),len(conf_new))
|
| 700 |
+
for i in range(len(new_lats)):
|
| 701 |
+
c_var = {0:"FCBK",1:"Zigzag"}
|
| 702 |
+
if isinstance(conf_new[indexs], torch.Tensor):
|
| 703 |
+
for z in range(len(conf_new[indexs])):
|
| 704 |
+
truncated_float = int(conf_new[indexs][z] * 100) / 100
|
| 705 |
+
temp_df = pd.DataFrame({'Sr.No':[s_no],'Latitude': [new_lats[i]], 'Longitude': [new_lons[i]],'Confidence':[truncated_float],"Class":[c_var[int(class_new[i][z].item())]]})
|
| 706 |
+
s_no+=1
|
| 707 |
+
# Concatenate the temporary DataFrame with the main DataFrame
|
| 708 |
+
df = pd.concat([df, temp_df], ignore_index=True)
|
| 709 |
+
else:
|
| 710 |
+
truncated_float = int(conf_new[indexs] * 100) / 100
|
| 711 |
+
temp_df = pd.DataFrame({'Sr.No':[s_no],'Latitude': [new_lats[i]], 'Longitude': [new_lons[i]],'Confidence':[truncated_float],"Class":[c_var[int(class_new[i].item())]]})
|
| 712 |
+
s_no+=1
|
| 713 |
+
df = pd.concat([df, temp_df], ignore_index=True)
|
| 714 |
+
indexs += 1
|
| 715 |
+
csv = df.to_csv(index=False).encode('utf-8')
|
| 716 |
+
if st.session_state.zoomed_in:
|
| 717 |
+
# indices_of_ones = np.array(indices_of_ones)
|
| 718 |
+
# latitudes = np.array(latitudes)
|
| 719 |
+
# longitudes = np.array(longitudes)
|
| 720 |
+
# lat_brick_kilns = lat_ones
|
| 721 |
+
# lon_brick_kilns = lon_ones
|
| 722 |
+
# indices_of_ones = indices_of_ones.tolist()
|
| 723 |
+
# latitudes = latitudes.tolist()
|
| 724 |
+
# longitudes = longitudes.tolist()
|
| 725 |
+
# num_bk = 0
|
| 726 |
+
# mid_lat = (box_lat1+box_lat2)/2
|
| 727 |
+
# mid_lon = (box_lon1+box_lon2)/2
|
| 728 |
+
# st.write(len(bk_lats),len(lat_x1),len(lat_x1_new),len(new_lats))
|
| 729 |
+
st.session_state.india_map=create_map(15,location = [mid_lat,mid_lon])
|
| 730 |
+
# rect_fg = folium.FeatureGroup()
|
| 731 |
+
poly_fg = folium.FeatureGroup()
|
| 732 |
+
# bounding_box_polygon.add_to(rect_fg)
|
| 733 |
+
# st.session_state.india_map.add_child(rect_fg)
|
| 734 |
+
for Idx in range(len(new_lats)):
|
| 735 |
+
lat = new_lats[Idx]
|
| 736 |
+
lon = new_lons[Idx]
|
| 737 |
+
if lat>=st.session_state.box_lat2 and lat<=st.session_state.box_lat1 and lon>=st.session_state.box_lon1 and lon<=st.session_state.box_lon2:
|
| 738 |
+
# continue
|
| 739 |
+
# st.write(lat,lon)
|
| 740 |
+
st.session_state.num_bk += 1
|
| 741 |
+
# add_locations(lat,lon,st.session_state.india_map)
|
| 742 |
+
add_box_to_map(lat_x1_new[Idx],lon_y1_new[Idx],lat_x2_new[Idx],lon_y2_new[Idx],lat_x3_new[Idx],lon_y3_new[Idx],lat_x4_new[Idx],lon_y4_new[Idx],class_new[Idx],poly_fg)
|
| 743 |
+
st.session_state.india_map.add_child(poly_fg)
|
| 744 |
+
st.session_state.zoomed_in = False
|
| 745 |
+
st.rerun()
|
| 746 |
+
# st.write("The number of brick kilns in the selected region is: ", st.session_state.num_bk)
|
| 747 |
+
# folium_static(india_map)
|
| 748 |
+
st.markdown("### Download options")
|
| 749 |
+
# with open('images_kiln.zip', 'rb') as zip_file:
|
| 750 |
+
# zip_data = zip_file.read()
|
| 751 |
+
# st.download_button(
|
| 752 |
+
# label="Download Kiln Images",
|
| 753 |
+
# data=zip_data,
|
| 754 |
+
# file_name='images_kiln.zip',
|
| 755 |
+
# mime="application/zip"
|
| 756 |
+
# )
|
| 757 |
+
# with open('images_no_kiln.zip', 'rb') as zip_file:
|
| 758 |
+
# zip_data = zip_file.read()
|
| 759 |
+
# st.download_button(
|
| 760 |
+
# label="Download Non-Kiln Images",
|
| 761 |
+
# data=zip_data,
|
| 762 |
+
# file_name='images_no_kiln.zip',
|
| 763 |
+
# mime="application/zip"
|
| 764 |
+
# )
|
| 765 |
+
st.download_button(label =
|
| 766 |
+
"Download CSV of latitude and longitude of brick kilns",
|
| 767 |
+
data = csv,
|
| 768 |
+
file_name = "lat_long.csv",
|
| 769 |
+
mime = "text/csv"
|
| 770 |
+
)
|
| 771 |
+
kml_content = generate_kml_content(new_lons, new_lats)
|
| 772 |
+
|
| 773 |
+
st.download_button(label =
|
| 774 |
+
"Download KML of latitude and longitude of brick kilns",
|
| 775 |
+
data = kml_content,
|
| 776 |
+
file_name = "points.kml",
|
| 777 |
+
mime = 'application/vnd.google-earth.kml+xml'
|
| 778 |
+
)
|
| 779 |
+
|
| 780 |
+
|
| 781 |
+
# Cleanup: Remove the temporary directory and zip file
|
| 782 |
+
# shutil.rmtree(temp_dir1)
|
| 783 |
+
# os.remove('images_kiln.zip')
|
| 784 |
+
# shutil.rmtree(temp_dir2)
|
| 785 |
+
# os.remove('images_no_kiln.zip')
|
| 786 |
+
|
| 787 |
+
# st.write(class_list)
|
| 788 |
+
# t=st.toggle("plots")
|
| 789 |
+
# if t:
|
| 790 |
+
# ####### Bounding Boxes ########
|
| 791 |
+
# st.write("Bounding Box Predictions!")
|
| 792 |
+
# st.write("There could be some predictions outside the bounding box as well!")
|
| 793 |
+
# ind = 0
|
| 794 |
+
# for i in indices_of_ones:
|
| 795 |
+
# r = results[i]
|
| 796 |
+
# # st.write(len(r.boxes.cls))
|
| 797 |
+
# annotator = Annotator(image_list[i])
|
| 798 |
+
# # image_lat = []
|
| 799 |
+
# # image_lon = []
|
| 800 |
+
# boxes = boxes_to_take[i]
|
| 801 |
+
# # x_centers = []
|
| 802 |
+
# # y_centers = []
|
| 803 |
+
# # st.write(len(boxes),len(r.boxes))
|
| 804 |
+
# for box in boxes:
|
| 805 |
+
# # st.write(box.xywh[0])
|
| 806 |
+
# # x_c,y_c,w,h = box.xywh[0]
|
| 807 |
+
# # x_c = x_c.item()
|
| 808 |
+
# # y_c = y_c.item()
|
| 809 |
+
# # result = project(lat_ones[ind], lon_ones[ind])
|
| 810 |
+
# # delta_y = y_c - 640
|
| 811 |
+
# # delta_x = x_c - 640
|
| 812 |
+
# # lat_value,lng_value = inverse_project(result[0]+delta_x,result[1]+delta_y)
|
| 813 |
+
# # bk_lats.append(lat_value)
|
| 814 |
+
# # bk_lons.append(lng_value)
|
| 815 |
+
# # x_centers.append(x_c)
|
| 816 |
+
# # y_centers.append(y_c)
|
| 817 |
+
# b = box.xyxyxyxy[0] # get box coordinates in (left, top, right, bottom) format
|
| 818 |
+
# c = box.cls
|
| 819 |
+
# if c.item() == 1:
|
| 820 |
+
# color = (0, 0, 255)
|
| 821 |
+
# else:
|
| 822 |
+
# color = (255, 0, 0)
|
| 823 |
+
|
| 824 |
+
# # list_box = b.tolist()
|
| 825 |
+
# # st.write(list_box)
|
| 826 |
+
# # two_point_list = [[list_box[0],list_box[1]],[list_box[2],list_box[3]]]
|
| 827 |
+
# annotator.box_label(b, model.names[int(c)], color=color,rotated=True)
|
| 828 |
+
# # write confidence to right of bounding boxes
|
| 829 |
+
# # annotator.text((b[0]+75, b[1]+75), f"{round(box.conf.item(),2)}",txt_color=color)
|
| 830 |
+
# # annotator.text((b[0]+85, b[1]+85), f"Lat-{b_lat},Lon-{b_lon}")
|
| 831 |
+
|
| 832 |
+
# img = annotator.result()
|
| 833 |
+
# # st.write(len(results))
|
| 834 |
+
# # if isinstance(prob_flat_list[ind], torch.Tensor):
|
| 835 |
+
# # list_of_probs = prob_flat_list[ind].tolist()
|
| 836 |
+
# # for z in range(len(list_of_probs)):
|
| 837 |
+
# # st.write(f"Latitude: {round(latitudes[i],2)}, Longitude: {round(longitudes[i],2)}, Confidence: {round(list_of_probs[z],2)}")
|
| 838 |
+
# # else:
|
| 839 |
+
# # st.write(f"Latitude: {round(latitudes[i],2)}, Longitude: {round(longitudes[i],2)}, Confidence: {round(prob_flat_list[ind],2)}")
|
| 840 |
+
|
| 841 |
+
# plt.figure(figsize=(8, 4))
|
| 842 |
+
# plt.imshow(img)
|
| 843 |
+
# plt.axis('off')
|
| 844 |
+
# plt.show()
|
| 845 |
+
# # plt.scatter(640, 640, c='r', s=40)
|
| 846 |
+
# # plt.scatter(640, 200, c='g', s=40)
|
| 847 |
+
# # for i in range(len(x_centers)):
|
| 848 |
+
# # plt.scatter(x_centers[i], y_centers[i], c='b', s=40)
|
| 849 |
+
# plt.title(f"Latitude: {round(lat_ones[ind],2)}, Longitude: {round(lon_ones[ind],2)}")
|
| 850 |
+
# plt.tight_layout()
|
| 851 |
+
# st.pyplot(plt)
|
| 852 |
+
# ind += 1
|
| 853 |
+
|
| 854 |
+
# if st.session_state.zoomed_in:
|
| 855 |
+
# # indices_of_ones = np.array(indices_of_ones)
|
| 856 |
+
# # latitudes = np.array(latitudes)
|
| 857 |
+
# # longitudes = np.array(longitudes)
|
| 858 |
+
# # lat_brick_kilns = lat_ones
|
| 859 |
+
# # lon_brick_kilns = lon_ones
|
| 860 |
+
# # indices_of_ones = indices_of_ones.tolist()
|
| 861 |
+
# # latitudes = latitudes.tolist()
|
| 862 |
+
# # longitudes = longitudes.tolist()
|
| 863 |
+
# st.session_state.india_map=create_map(13)
|
| 864 |
+
# bounding_box_polygon.add_to(st.session_state.india_map)
|
| 865 |
+
# for Idx in range(len(bk_lats)):
|
| 866 |
+
# lat = bk_lats[Idx]
|
| 867 |
+
# lon = bk_lons[Idx]
|
| 868 |
+
# add_locations(lat,lon,st.session_state.india_map)
|
| 869 |
+
# st.session_state.zoomed_in = False
|
| 870 |
+
# st.experimental_rerun()
|
| 871 |
+
|
| 872 |
+
|
| 873 |
+
############## GradCAM ##############
|
| 874 |
+
# last_conv_layer_name = "block5_conv3"
|
| 875 |
+
# st.write("Let's see how well our model is identifying the pattern of brick kilns in the images.")
|
| 876 |
+
# for idx in indices_of_ones:
|
| 877 |
+
|
| 878 |
+
# st.write("Predicted Probability: ", round(predictions_prob[idx][0],2))
|
| 879 |
+
|
| 880 |
+
# # Load and preprocess the original image
|
| 881 |
+
# img_array = images[idx:idx+1]
|
| 882 |
+
|
| 883 |
+
# # Create a figure and axes for the images
|
| 884 |
+
# fig, axs = plt.subplots(1, 2, figsize=(10, 5), gridspec_kw={'width_ratios': [1.2, 1.44]})
|
| 885 |
+
|
| 886 |
+
# # Display the original image
|
| 887 |
+
# axs[0].imshow(images[idx])
|
| 888 |
+
# axs[0].set_title('Original Image',size="xx-large")
|
| 889 |
+
|
| 890 |
+
# # Preprocess the image for GradCAM
|
| 891 |
+
# img_array = imgs_input_fn(img_array)
|
| 892 |
+
|
| 893 |
+
# # Generate class activation heatmap
|
| 894 |
+
# heatmap = make_gradcam_heatmap(img_array, model, last_conv_layer_name)
|
| 895 |
+
|
| 896 |
+
# # Generate and display the GradCAM superimposed image
|
| 897 |
+
# grad_fig = save_and_display_gradcam(images[idx], heatmap)
|
| 898 |
+
# grad_plot = axs[1].imshow(grad_fig, cmap='jet', vmin=0, vmax=1)
|
| 899 |
+
# axs[1].set_title('GradCAM Superimposed',size="xx-large")
|
| 900 |
+
# cbar = plt.colorbar(grad_plot, ax=axs[1], pad=0.02, shrink=0.91)
|
| 901 |
+
# cbar.set_label('Heatmap Intensity')
|
| 902 |
+
# cbar.ax.tick_params(labelsize=30)
|
| 903 |
+
|
| 904 |
+
# for ax in axs:
|
| 905 |
+
# ax.axis('off')
|
| 906 |
+
# plt.tight_layout()
|
| 907 |
+
# st.pyplot(fig)
|
| 908 |
+
|
| 909 |
+
else:
|
| 910 |
+
st.write("No Brick Kilns detected in the selected region!")
|
| 911 |
+
# with open('images_no_kiln.zip', 'rb') as zip_file:
|
| 912 |
+
# zip_data = zip_file.read()
|
| 913 |
+
# st.download_button(
|
| 914 |
+
# label="Download Non-Kiln Images",
|
| 915 |
+
# data=zip_data,
|
| 916 |
+
# file_name='images_no_kiln.zip',
|
| 917 |
+
# mime="application/zip"
|
| 918 |
+
# )
|
| 919 |
+
# shutil.rmtree(temp_dir2)
|
| 920 |
+
# os.remove('images_no_kiln.zip')
|
| 921 |
+
|
| 922 |
+
else:
|
| 923 |
+
st.write(":red[The bounding box area is too big. The area should be less than or equal to 0.005 sq units]")
|
| 924 |
+
|
| 925 |
+
|
| 926 |
+
|
| 927 |
+
|
| 928 |
+
|
| 929 |
+
if __name__ == "__main__":
|
| 930 |
+
main()
|
packages.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
libgl1
|
requirements (1).txt
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
folium
|
| 2 |
+
gdown
|
| 3 |
+
huggingface-hub
|
| 4 |
+
matplotlib
|
| 5 |
+
numpy
|
| 6 |
+
opencv-python-headless
|
| 7 |
+
pandas
|
| 8 |
+
requests
|
| 9 |
+
scikit-learn
|
| 10 |
+
streamlit-aggrid
|
| 11 |
+
streamlit-folium
|
| 12 |
+
tensorflow
|
| 13 |
+
torch
|
| 14 |
+
streamlit==1.33.0
|
| 15 |
+
ultralytics==8.2.1
|
| 16 |
+
xarray
|
| 17 |
+
simplekml
|
| 18 |
+
dill
|