File size: 8,094 Bytes
28700b8
 
 
 
 
 
 
 
bf7c2da
 
 
28700b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf7c2da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28700b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf7c2da
28700b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf7c2da
28700b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
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.")