Commit 501373ca authored by Jean-Marie Lepioufle's avatar Jean-Marie Lepioufle
Browse files

Initial commit

parents
The MIT License (MIT)
Copyright © 2021 NILU
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# osmaug v0.01dev
A package for:
- getting OpenStreet Map pictures around specific locations.
- implementing simple picture augmentation.
## Install
Package 'osmaug' require [geckodriver](https://github.com/mozilla/geckodriver/releases).
```bash
cd /tmp
git clone https://git.nilu.no/aqdl/osmaug_pkg.git
cd osmaug_pkg
pip3 install -e .
```
## Usage
```bash
python osmaug/getosm.py -c config.json
python osmaug/augmosm.py -c config.json
```
## Example
```bash
python osmaug/getosm.py -c osmaug/example/osm.json
python osmaug/augmosm.py -c osmaug/example/augmosm.json
```
## Related works
The package is a close adaptation of : [osm2img](https://git.nilu.no/deepair/osm2img),[osmsubsetter](https://git.nilu.no/deepair/osmsubsetter),[imgaug](https://git.nilu.no/deepair/imgaug).
import argparse
from typing import Dict
import json
import pandas as pd
import os
from skimage import io, img_as_float, img_as_ubyte
from PIL import Image
import numpy as np
from osmaug.dictionnary.dictionnary_tf import augm_dict
from osmaug.transformation.crop import crop
def augmosm_function(params: Dict):
workdir = os.path.join(params['workdir'])
if not os.path.exists(workdir):
sys.exit('workdir does not exist: '+workdir)
resdir = os.path.join(workdir,"augm")
if not os.path.exists(resdir):
os.mkdir(resdir)
print("resdir: "+resdir)
files = pd.DataFrame.from_dict(params['files'], orient='columns')
for index, row in files.iterrows():
print("-> "+row['name'])
img = img_as_float(io.imread(os.path.join(workdir,row["name"])))
augm = augm_dict[row['augmentation']]
img = augm(img)
img = crop(img, delta=row["delta_pixel"])
pil_img = Image.fromarray(img_as_ubyte(img)).save(os.path.join(resdir,"aug_"+row['augmentation']+"_"+row["name"]))
def main():
"""
Main augmosm_function.
"""
parser = argparse.ArgumentParser(description="Argument parsing for augmenting osm pictures")
parser.add_argument("-c", help="Config")
args = parser.parse_args()
with open(args.c,encoding='utf8') as f:
augmosm_config = json.load(f)
augmosm_function(augmosm_config)
print("OSM pictures augmentation completed.")
if __name__ == "__main__":
main()
from osmaug.transformation.affine import tf_from_center_random
augm_dict = {
"affineRandom": tf_from_center_random}
{
"files" : [
{
"name": "bygdøy_zoom_19.jpg", "augmentation" : "affineRandom", "delta_pixel" : 112
},
{
"name": "alna_zoom_19.jpg" , "augmentation" : "affineRandom", "delta_pixel" : 112
}
],
"workdir" : "C:/Users/jml/Documents/osm"
}
{
"points" : [
{
"name": "bygdøy", "coords" : [59.919306, 10.6965], "conv_crs" : "+proj=utm +zone=32V, +north +ellps=WGS84 +datum=WGS84 +units=m +no_defs", "delta_meters" : 100
},
{
"name": "alna" , "coords" : [59.927689, 10.846545], "conv_crs" : "+proj=utm +zone=32V, +north +ellps=WGS84 +datum=WGS84 +units=m +no_defs", "delta_meters" : 100
}
],
"zoom" : 19,
"workdir" : "C:/Users/jml/Documents/",
"driver_bin" : "C:/Users/jml/Documents/geckodriver.exe"
}
import argparse
from typing import Dict
import json
import pandas as pd
import os
from osmaug.osm.map import make_bbox, load_map, map2png, png2jpg
def getosm_function(params: Dict):
driver_bin = params['driver_bin']
workdir = os.path.join(params['workdir'])
if not os.path.exists(workdir):
sys.exit('workdir does not exist: '+workdir)
resdir = os.path.join(workdir,"osm")
if not os.path.exists(resdir):
os.mkdir(resdir)
print("resdir: "+resdir)
zoom = params['zoom']
points = pd.DataFrame.from_dict(params['points'], orient='columns')
for index, row in points.iterrows():
print("-> "+row['name'])
tmp = make_bbox(row['coords'],row['conv_crs'],row['delta_meters'])
file = os.path.join(resdir,row['name']+'_zoom_'+str(zoom)+'.html')
load_map(tmp,zoom,file)
tmp = map2png(file, 5, driver_bin)
tmp = png2jpg(tmp)
def main():
"""
Main get_osm_rgb function.
"""
parser = argparse.ArgumentParser(description="Argument parsing for getting osm pictures")
parser.add_argument("-c", help="Config")
args = parser.parse_args()
with open(args.c,encoding='utf8') as f:
getosm_config = json.load(f)
getosm_function(getosm_config)
print("Getting OSM as RGB picture completed.")
if __name__ == "__main__":
main()
from pyproj import Proj
import time
from folium import Map
from selenium import webdriver
from PIL import Image
# [59.92773,10.84633]
def make_bbox(coords,crs,delta_meters):
"""
Make a bbox from a location in long/lat
"""
utmproj = Proj(crs)
# latlong2utm
utmx, utmy = utmproj(coords[1], coords[0])
# utm2latlong + delta for bbox
ll_lon, ll_lat = utmproj(utmx - delta_meters,utmy - delta_meters, inverse=True)
ur_lon, ur_lat = utmproj(utmx + delta_meters,utmy + delta_meters, inverse=True)
#bbox
res = [ll_lat,ll_lon,ur_lat,ur_lon]
return(res)
# bbox=[59.8,10.7, 60.0, 10.8]
def load_map(bbox,zoom,file):
"""
Load OSM leaflet and save it.
"""
# lat/long
center=[bbox[0]+(bbox[2]-bbox[0])/2,bbox[1]+(bbox[3]-bbox[1])/2]
bounds=[[bbox[0],bbox[1]],[bbox[2],bbox[3]]]
# get map
m = Map(center, control_scale=True, zoom_start=zoom)
m.fit_bounds(bounds, max_zoom=zoom)
m.save(file)
def map2png(file, delay, driver_bin):
"""
Convert .html map tile to .png and save it.
"""
driver = webdriver.Firefox(executable_path=driver_bin)
driver.get('file://{}'.format(file))
# Give the map tiles some time to load
time.sleep(delay)
print(file)
driver.save_screenshot(file.replace('.html', '.png'))
driver.quit()
return(file.replace('.html', '.png'))
def png2jpg(file):
"""
Convert image file from .png to .jpg and save it.
"""
img = Image.open(file).convert('RGB')
img.save(file.replace('.png','.jpg'))
return(file.replace('.png','.jpg'))
import random
import numpy as np
from skimage import io, transform, util
def tf_from_center_random(img: np.ndarray):
"""
Transform an image around its center with random rotation, random shear and reflection
"""
# For a transformatino around the center of the image
# one compose a translation to change the origin, a transformatino, and finally the inverse of the first translation.
# https://scikit-image.org/docs/stable/auto_examples/transform/plot_transform_types.html#sphx-glr-auto-examples-transform-plot-transform-types-py
shift = transform.EuclideanTransform(translation=-np.array([img.shape[1],img.shape[0]]) / 2)
# random rotation between -pi and pi
rotation = transform.EuclideanTransform(rotation=random.uniform(-np.pi, np.pi))
# shear parallel to the x-axis.
# https://en.wikipedia.org/wiki/Transformation_matrix
# A shear parallel to the y axis has x' = x + ky and y' = y. Written in matrix form.
# Random shear between 0.1 and 0.3
shear_x = np.array([[1, random.uniform(0.1, 0.3), 0],
[0, 1, 0],
[0, 0, 1]])
# shear parallel to the x-axis:
#A shear parallel to the y axis has x' = x and y' = kx + y. Written in matrix form.
# Random shear between 0.1 and 0.3
shear_y = np.array([[1, 0, 0],
[random.uniform(0.1, 0.3), 1, 0],
[0, 0, 1]])
# reflection if true or none otherwise
refl_bool = random.sample([True,False],1)
if refl_bool[0]:
reflection = np.array([[1, 0, 0],
[0,-1, 0],
[0, 0, 1]])
else:
reflection = np.array([[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
# transformation matrix
matrix = np.linalg.inv(shift.params) @ reflection @ shear_x @ shear_y @ rotation.params @ shift.params
tform = transform.EuclideanTransform(matrix)
tf_img = transform.warp(img, tform.inverse)
return(tf_img)
import numpy as np
def crop(img: np.ndarray, delta: int=112):
h, w, _ = img.shape
cx = int(w / 2)
cy = int(h / 2)
x1 = cx - delta
x2 = cx + delta
y1 = cy - delta
y2 = cy + delta
return img[y1:y2, x1:x2, :]
scikit-learn~=0.24.1
pandas~=1.2.4
numpy~=1.20.2
argparse~=1.1
pyproj~=3.0.1
folium~=0.12.1
selenium~=3.141.0
scikit-image~=0.18.1
from setuptools import setup
import os
with open('README.md', 'r') as fh:
long_description = fh.read()
library_folder = os.path.dirname(os.path.realpath(__file__))
requirementPath = f'{library_folder}/requirements.txt'
install_requires = []
if os.path.isfile(requirementPath):
with open(requirementPath) as f:
install_requires = f.read().splitlines()
dev_requirements = []
setup(
name='osmaug',
version='0.01dev',
author='Jean-Marie Lepioufle, Islen Vallejo',
author_email='jml@nilu.no, iv@nilu.no',
packages=[
'osmaug',
'osmaug.osm',
'osmaug.transformation'],
license='MIT + Copyright NILU',
description='A package for getting OpenStreet Map pictures and implementing augmentation.',
long_description = long_description,
url='https://git.nilu.no/aqdl/osmaug',
python_requires='>=3.9',
install_requires=install_requires,
extras_require={
'dev': dev_requirements})
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment