JertineTech / app.py
JertineAI's picture
Update app.py
bf7c2da verified
import streamlit as st
import cv2
import folium
import geopandas as gpd
import pandas as pd
from PIL import Image
import numpy as np
from streamlit_folium import st_folium
from typing import Dict, List
import requests
from time import sleep
def process_image(image_path):
# Read the image
img = cv2.imread(image_path)
# Apply image processing techniques (e.g., noise reduction, edge detection)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
edges = cv2.Canny(blur, 100, 200)
# Dummy analysis results
results = {
'Topography': 'Mountainous',
'Forestry Pattern': 'Dense Forest',
'Ocean Pattern': 'Calm',
'Geological Features': 'Mountains, Rivers'
}
return img, edges, results
def display_images(images):
# Generate captions for each pair of images
captions = []
for i in range(0, len(images), 2):
captions.append(f'Original Image {i//2 + 1}')
captions.append(f'Processed Image {i//2 + 1}')
# Display images
st.image(images, caption=captions, width=300)
def display_results(results):
st.write("### Analysis Results")
for key, value in results.items():
st.write(f"{key}: {value}")
def export_results(results, export_format):
results_df = pd.DataFrame(results)
if export_format == "Excel (.xlsx)":
results_df.to_excel('analysis_results.xlsx', index=False)
st.success("Results exported to analysis_results.xlsx")
elif export_format == "CSV (.csv)":
results_df.to_csv('analysis_results.csv', index=False)
st.success("Results exported to analysis_results.csv")
elif export_format == "JSON (.json)":
results_df.to_json('analysis_results.json', orient='records')
st.success("Results exported to analysis_results.json")
def create_map(location_name, latitude, longitude):
map = folium.Map(location=[latitude, longitude], zoom_start=10)
folium.Marker(location=[latitude, longitude], popup=location_name).add_to(map)
return map
def analyze_location(location_name, latitude, longitude):
location_info = {
'Location Name': location_name,
'Latitude': latitude,
'Longitude': longitude,
}
# Get address data from Nominatim API
nominatim_url = f"https://nominatim.openstreetmap.org/reverse?format=json&lat={latitude}&lon={longitude}&zoom=10"
headers = {'User-Agent': 'DroneImageProcessor/1.0'}
response = requests.get(nominatim_url, headers=headers)
sleep(1) # Respect rate limiting
if response.status_code == 200:
osm_data = response.json()
address = osm_data.get('address', {})
# Extract relevant information
location_info.update({
'Country': address.get('country', 'Unknown'),
'State/Region': address.get('state', address.get('region', 'Unknown')),
'City': address.get('city', address.get('town', address.get('village', 'Unknown'))),
'Land Use': address.get('landuse', 'Unknown'),
})
# Get elevation data from OpenTopoData API
elevation_url = f"https://api.opentopodata.org/v1/aster30m?locations={latitude},{longitude}"
response = requests.get(elevation_url)
sleep(1) # Respect rate limiting
if response.status_code == 200:
elevation_data = response.json()
elevation = elevation_data['results'][0]['elevation']
location_info['Elevation'] = f"{elevation:.1f} meters"
# Basic terrain classification based on elevation
if elevation < 100:
terrain = "Lowland"
elif elevation < 500:
terrain = "Hills"
else:
terrain = "Mountains"
location_info['Terrain Type'] = terrain
return location_info
# Streamlit app
st.title("Drone Image Processing")
# Input for location details
location_name = st.text_input("Location Name")
latitude_deg = st.number_input("Latitude (degrees)", format="%f")
latitude_dir = st.selectbox("Latitude Direction", ["N", "S"])
longitude_deg = st.number_input("Longitude (degrees)", format="%f")
longitude_dir = st.selectbox("Longitude Direction", ["E", "W"])
# Convert latitude and longitude to decimal degrees
latitude = latitude_deg if latitude_dir == "N" else -latitude_deg
longitude = longitude_deg if longitude_dir == "E" else -longitude_deg
# Enter button to find and display the location on the map
if st.button("Enter"):
map = create_map(location_name, latitude, longitude)
location_info = analyze_location(location_name, latitude, longitude)
st.write("### Location Information")
for key, value in location_info.items():
st.write(f"{key}: {value}")
st_folium(map, width=700, height=500)
# File upload
uploaded_files = st.file_uploader("Upload Images", type=["jpg", "jpeg", "png"], accept_multiple_files=True)
if uploaded_files and location_name and latitude and longitude:
images = []
results_list = []
for uploaded_file in uploaded_files:
# Save the uploaded file to a temporary location
with open(f"temp_{uploaded_file.name}", "wb") as f:
f.write(uploaded_file.getbuffer())
# Process the image
original_img, processed_img, results = process_image(f"temp_{uploaded_file.name}")
# Append images and results
images.append(original_img)
images.append(processed_img)
results_list.append(results)
# Display images
display_images(images)
# Display results
combined_results: Dict[str, List[Dict[str, str]]] = {
'Geological Analysis': [],
'Agricultural and Environmental Analysis': [],
'Urbanisation and Population Analysis': []
}
for i, results in enumerate(results_list):
st.write(f"### Results for Image {i+1}")
display_results(results)
combined_results['Geological Analysis'].append({
'Topography': results['Topography'],
'Geological Features': results['Geological Features']
})
combined_results['Agricultural and Environmental Analysis'].append({
'Forestry Pattern': results['Forestry Pattern'],
'Ocean Pattern': results['Ocean Pattern']
})
combined_results['Urbanisation and Population Analysis'].append({
'Urbanisation Impact': 'Not implemented'
})
# Export options
st.sidebar.subheader("Export Options")
export_format = st.sidebar.radio(
"Export Format",
["Excel (.xlsx)", "CSV (.csv)", "JSON (.json)"]
)
# Export results button
if st.sidebar.button("Export Results"):
export_results(combined_results, export_format)
# Filter results
st.write("### Filter Results")
filter_option = st.selectbox("Select Analysis Type", ["Geological Analysis", "Agricultural and Environmental Analysis", "Urbanisation and Population Analysis"])
if filter_option == "Geological Analysis":
st.write("### Geological Analysis Results")
for i, results in enumerate(combined_results['Geological Analysis']):
st.write(f"### Results for Image {i+1}")
st.write(f"Topography: {results['Topography']}")
st.write(f"Geological Features: {results['Geological Features']}")
elif filter_option == "Agricultural and Environmental Analysis":
st.write("### Agricultural and Environmental Analysis Results")
for i, results in enumerate(combined_results['Agricultural and Environmental Analysis']):
st.write(f"### Results for Image {i+1}")
st.write(f"Forestry Pattern: {results['Forestry Pattern']}")
st.write(f"Ocean Pattern: {results['Ocean Pattern']}")
elif filter_option == "Urbanisation and Population Analysis":
st.write("### Urbanisation and Population Analysis Results")
for i, results in enumerate(combined_results['Urbanisation and Population Analysis']):
st.write(f"### Results for Image {i+1}")
st.write("Urbanisation and Population Analysis not implemented yet.")