Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Heisann, sanderscript er fikset #163

Merged
merged 2 commits into from
Feb 19, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 65 additions & 21 deletions WMS/Sanderscript.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,49 @@
#Dette scriptet genererer treningsdata

import os
import urllib.parse
import json
import requests
from datetime import datetime

def generate_wms_getmap_url():
def generate_wms_picture():

# Base URL of the WMS service
# URL til WMS
base_url = "https://openwms.statkart.no/skwms1/wms.fkb"

# Common WMS parameters with static values
# Bruker riktig path til scriptet
current_script_directory = os.path.dirname(os.path.abspath(__file__))

# Leser koordinatene fra JSON-filen
coordinates_file_path = os.path.join(current_script_directory, 'resources', 'coordinates.json')
with open(coordinates_file_path) as file:
data = json.load(file)
coordinates = data['Coordinates']

# Beregner bbox fra koordinatene gitt i json fila
min_x = min(coord[0] for coord in coordinates)
min_y = min(coord[1] for coord in coordinates)
max_x = max(coord[0] for coord in coordinates)
max_y = max(coord[1] for coord in coordinates)
bbox = f'{min_x},{min_y},{max_x},{max_y}'

# Velger et sted å lagre bildene
images_directory = "Fasitfoto"

# Lagrer alt i mappen definert
images_directory_path = os.path.join(images_directory)

# Sjekker om filen eksisterer
os.makedirs(images_directory_path, exist_ok=True)

# WMS parametere, de tomme feltene blir definert videre i koden
wms_params = {
'SERVICE': 'WMS',
'VERSION': '1.3.0',
'REQUEST': 'GetMap',
'BBOX': '86862.34650433670322,6466039.970492540859,87579.68362640209671,6466748.95569468569',
'CRS': 'EPSG:25833',
'WIDTH': '774',
'HEIGHT': '764',
'BBOX': bbox,
'CRS': 'EPSG:25832',
'WIDTH': '1600',
'HEIGHT': '1600',
'LAYERS': '',
'STYLES': '',
'FORMAT': 'image/png',
Expand All @@ -26,17 +54,16 @@ def generate_wms_getmap_url():
'sld_body': ''
}

# Ask user for input for layers
# Spør som en input hvilket "Layers brukeren vil se"
layer_names = input("Enter LAYERS (layer names, comma-separated if multiple, Current layers are: veg,bru,bygning): ")
wms_params['LAYERS'] = layer_names


# Start the SLD body
# Starter SLD body
sld_body = '''
<sld:StyledLayerDescriptor version="1.0.0" xmlns:sld="http://www.opengis.net/sld" xmlns:ogc="http://www.opengis.net/ogc" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/sld StyledLayerDescriptor.xsd">
'''
<sld:StyledLayerDescriptor version="1.0.0" xmlns:sld="http://www.opengis.net/sld" xmlns:ogc="http://www.opengis.net/ogc" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/sld StyledLayerDescriptor.xsd">
'''

# Generate a NamedLayer block for each layer
# Genererer en "NamedLayer" blokk av kode for hvert layer
for layer_name in layer_names.split(','):
sld_body += f'''
<sld:NamedLayer>
Expand All @@ -57,22 +84,39 @@ def generate_wms_getmap_url():
</sld:NamedLayer>
'''

# Close the SLD body
# Lukker SLD bodyen
sld_body += '</sld:StyledLayerDescriptor>'

# Assign the complete SLD body to the wms_params
# Putter SLD stylingen inn i wms_params
wms_params['sld_body'] = sld_body

# Encode parameters, including SLD body
encoded_params = urllib.parse.urlencode(wms_params, quote_via=urllib.parse.quote)

# Build and print the full URL
# Bygger og printer URLen med de riktige definerte WMS parameterene
full_url = f"{base_url}?{encoded_params}"
print("Generated URL:")
print(full_url)

# Return the full URL
return full_url
# Headers som lager en browser request
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
}

response = requests.get(full_url, headers=headers)

if response.status_code == 200:
# Genererer et filnavn basert på dato og tid bildet ble hentet på
timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
file_name = f"output_{timestamp}.png"

# Hele fil pathen
image_path = os.path.join(images_directory_path, file_name)

# Generate the URL
generated_url = generate_wms_getmap_url()
with open(image_path, 'wb') as file:
file.write(response.content)
print(f"Bildet ble lagret i {image_path}.")
else:
print(f"Kunne ikke lagre bilde, statuskode: {response.status_code}")

generate_wms_picture()