Skip to content

Commit b01977d

Browse files
author
Nicolás Guardo
committed
First commit and upload to repository
0 parents  commit b01977d

File tree

2 files changed

+207
-0
lines changed

2 files changed

+207
-0
lines changed

image_processing.py

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import os
2+
import glob
3+
from pathlib import Path
4+
import numpy as np
5+
import rasterio
6+
from matplotlib import pyplot as plt
7+
8+
9+
def load_image_bands(image_folder: str, bands: list, pattern_str: str, file_ext: str = "TIF") -> dict:
10+
"""
11+
Function fot loading the individual bands of a raster.
12+
:param image_folder:
13+
:param bands:
14+
:param pattern_str:
15+
:param file_ext:
16+
:return: dict
17+
"""
18+
band_dict = {}
19+
path = Path(image_folder)
20+
for band in bands:
21+
file = next(path.glob(f"{pattern_str}{band}.{file_ext}"))
22+
dataset = rasterio.open(file)
23+
band_dict.update({band: dataset.read(1)})
24+
dataset.close()
25+
26+
return band_dict
27+
28+
29+
def display_rgb(bands, red_channel, green_channel, blue_channel):
30+
rgb = np.stack([bands[red_channel], bands[green_channel], bands[blue_channel]], axis=-1)
31+
rgb = rgb / rgb.max()
32+
33+
34+
def stack_bands(image_path: str, image_folder: str, file_pattern: str, output_raster: str, metadata: dict, sort=True):
35+
os.chdir(image_path)
36+
37+
files = glob.glob(f"{image_folder}/{file_pattern}")
38+
39+
if sort:
40+
files.sort()
41+
else:
42+
files.sort(reverse=True)
43+
44+
with rasterio.open(output_raster, "w", metadata) as output:
45+
for index, filepath in enumerate(files, start=1):
46+
source = rasterio.open(filepath)
47+
output.write(source.read(1), index)
48+
source.close()
49+
50+
51+
52+
stack_bands("C:\\Users\\orden\\Desktop\\Teledeteccion_QGIS\\ImagenesLandsat",
53+
"LT05_L1TP_229092_19860116_20200918_02_T1", "*_B*.TIF")

vector_conversion.py

+154
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
# Imports
2+
import numpy as np
3+
import pandas as pd
4+
from shapely.geometry import Point, MultiPoint, LineString, Polygon
5+
import geopandas as gpd
6+
7+
8+
def extract_coordinates(line: str) -> tuple:
9+
"""
10+
Function used to extract coordinates from a string in the form x,y\n read from a txt file
11+
1. Convert the line into a list using the split method
12+
2. Select the first element in the list (which should be the x coordinate) and convert it into a float type
13+
3. Select the second element in the list (which should be the y coordinate), slice it until the last element (-1 - \n)
14+
and convert it into a float number
15+
16+
The function returns a tuple in the form (x,y)
17+
"""
18+
pair = line.split(",")
19+
x = float(pair[0])
20+
y = float(pair[1][:-1])
21+
coordinates = (x, y)
22+
return coordinates
23+
24+
25+
def txt_to_vector_layer(txt_filepath: str, dst_filepath: str = None, driver: str = None, geom_type="Point",
26+
epsg=4326) -> gpd.GeoDataFrame:
27+
"""
28+
Function created to convert a txt file to a simple vector layer
29+
30+
:param txt_filepath: Filepath to the txt file
31+
:param dst_filepath: None The vector layer's output filepath in case of saving
32+
:param driver: None The vector layer's driver in case of saving
33+
:param geom_type: Point The geometry type of the vector layer
34+
:param epsg: 4326 The Coordinate Reference System of the layer
35+
:return: GeoPandas GeoDataFrame of and output file
36+
"""
37+
# Open the txt file
38+
with open(txt_filepath) as txt_file:
39+
lines = txt_file.readlines()
40+
txt_file.close()
41+
42+
coords_list = [] # empty list
43+
44+
for line in lines:
45+
coord_pair = extract_coordinates(line)
46+
coords_list.append(coord_pair)
47+
48+
if geom_type == "Point": # Point geometry vector layer
49+
50+
geometry = pd.Series(coords_list).apply(Point)
51+
df = pd.DataFrame({"geometry": geometry})
52+
gdf = gpd.GeoDataFrame(df, crs=epsg)
53+
54+
return gdf.to_file(dst_filepath, driver=driver) if dst_filepath else gdf
55+
56+
elif geom_type == "MultiPoint": # MultiPoint geometry vector layer
57+
58+
geometry = MultiPoint(coords_list)
59+
df = pd.DataFrame({"geometry": [geometry]})
60+
gdf = gpd.GeoDataFrame(df, crs=epsg)
61+
62+
return gdf.to_file(dst_filepath, driver=driver) if dst_filepath else gdf
63+
64+
elif geom_type == "LineString": # LineString geometry vector layer
65+
66+
geometry = LineString(coords_list)
67+
df = pd.DataFrame({"geometry": [geometry]})
68+
gdf = gpd.GeoDataFrame(df, crs=epsg)
69+
70+
return gdf.to_file(dst_filepath, driver=driver) if dst_filepath else gdf
71+
72+
elif geom_type == "Polygon": # Poygon geometry vector layer
73+
74+
if coords_list[0] == coords_list[-1]:
75+
geometry = Polygon(coords_list)
76+
df = pd.DataFrame({"geometry": [geometry]})
77+
gdf = gpd.GeoDataFrame(df, crs=epsg)
78+
79+
return gdf.to_file(dst_filepath, driver=driver) if dst_filepath else gdf
80+
81+
else:
82+
raise Exception("To construct a Polygon geometry, make sure the first and last point are identical")
83+
84+
85+
def csv_to_vector_layer(csv_filepath: str, x_column: str, y_column: str, dst_filepath=None, driver=None,
86+
geom_type="Point", epsg=4326):
87+
88+
"""
89+
Function to create a vector layer from a csv file.
90+
:param csv_filepath: path corresponding to the csv file
91+
:param x_column: column containing longitude values
92+
:param y_column: column containing latitude values
93+
:param dst_filepath: If wanted, path to export the file
94+
:param driver: driver to export the file
95+
:param geom_type: geometry type
96+
:param epsg: EPSG code of the geometry
97+
:return:
98+
"""
99+
if geom_type == "Point":
100+
df = pd.read_csv(csv_filepath)
101+
geometry = gpd.points_from_xy(df[x_column], df[y_column], crs=epsg)
102+
gdf = gpd.GeoDataFrame(df, geometry=geometry)
103+
104+
return gdf
105+
106+
elif geom_type == "LineString":
107+
df = pd.read_csv(csv_filepath)
108+
geometry = gpd.points_from_xy(df[x_column], df[y_column], crs=epsg) # GeometryArray 1D
109+
geometry = LineString(geometry)
110+
111+
gdf = gpd.GeoDataFrame({"tipo":["cuenca"], "geometry":[geometry]})
112+
113+
return gdf
114+
115+
# txt_to_vector_layer(
116+
# txt_filepath="C:\\Users\\orden\\Desktop\\Codigo\\data\\Cuenca_Parana.txt",
117+
# dst_filepath="C:\\Users\\orden\\Desktop\\Codigo\\data\\Polygon_Cuenca_Parana.shp",
118+
# driver="Shapefile",
119+
# geom_type="Polygon"
120+
# )
121+
122+
gdf = csv_to_vector_layer("C:\\Users\\orden\\Desktop\\Codigo\\data\\Cuenca_Parana.csv", "Longitud", "Latitud", geom_type="LineString")
123+
124+
print(gdf)
125+
126+
# df_cuenca_parana_point["geometry"] = df_cuenca_parana_point["geometry"].apply(Point)
127+
#
128+
# gdf_cuenca_parana_point = gpd.GeoDataFrame(df_cuenca_parana_point, geometry="geometry", crs=4326)
129+
130+
# POLYLINE (LINESTRING)
131+
132+
# 1° opcion
133+
# df_cuenca_parana_line = pd.DataFrame({"nombre":"Cuenca Paraná", "geometry":[cuenca_parana]})
134+
# df_cuenca_parana_line["geometry"] = df_cuenca_parana_line["geometry"].apply(LineString)
135+
136+
# 2° opcion
137+
# cca_parana_linestring = LineString(cuenca_parana)
138+
# df_cuenca_parana_line = pd.DataFrame({"nombre":"Cuenca Paraná", "geometry":[cca_parana_linestring]})
139+
140+
# gdf_cuenca_parana_line = gpd.GeoDataFrame(df_cuenca_parana_line, geometry="geometry", crs=4326)
141+
# gdf_cuenca_parana_line.to_file("C:/Users/Orden/Downloads/Cuenca_Parana.shp")
142+
143+
# POLYGON
144+
145+
# 1° opcion
146+
# df_cuenca_parana_polyg = pd.DataFrame({"nombre":"Cuenca Paraná", "geometry":[cuenca_parana]})
147+
# df_cuenca_parana_polyg["geometry"] = df_cuenca_parana_polyg["geometry"].apply(Polygon)
148+
149+
# 2° opcion
150+
# cca_parana_polyg = Polygon(cuenca_parana)
151+
# df_cuenca_parana_polyg = pd.DataFrame({"nombre":"Cuenca Paraná", "geometry":[cca_parana_polyg]})
152+
153+
# gdf_cuenca_parana_polyg = gpd.GeoDataFrame(df_cuenca_parana_polyg, geometry="geometry", crs=4326)
154+
# gdf_cuenca_parana_polyg.to_file("C:/Users/Orden/Downloads/Cuenca_Parana_Polyg.shp")

0 commit comments

Comments
 (0)