Dimensions of the VNIR datacube: (1172, 66, 1299)
Dimensions of the image: 1172 1299
Dimensions of the pre-processed RGB image: (3, 1172, 1299)
Dimensions of the post-processed RGB image: (1172, 1299, 3)
# Importing the shapefile for CASI
shape_path = cwd + os.path.sep + 'acquisitions' + os.path.sep + 'shapefile_EPSG4326.shp'
fields_shp = gpd.read_file(shape_path)
fields_shp
Plotting the Tuscany region
Plotting the PRISMA image over the Tuscany region
RGB composition of the PRISMA image
C:\\Users\\dario\\anaconda3\\lib\\site-packages\\ipykernel_launcher.py:24: MatplotlibDeprecationWarning:
The dedent function was deprecated in Matplotlib 3.1 and will be removed in 3.3. Use inspect.cleandoc instead.
Crop fields over the PRISMA image
Collecting the PRISMA pixels within the crop fields
Plotting the corn and the tomato spectral curves
Creating the training and the test datasets
tomato points: 487
corn points: 1690
Defining the 1D model
Training and testing the model
from mpl_toolkits.basemap import Basemap
import matplotlib.patches as mpatches
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
import tensorflow as tf
from tensorflow.keras.layers import Conv1D, MaxPooling1D, Dropout, Flatten, Dense
from tensorflow.keras import Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.regularizers import l2
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping
from numpy import save
import os
import os.path
import numpy as np
from numpy.random import seed
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix,classification_report
import pickle
import h5py
import geopandas as gpd
import gdal
import matplotlib.pyplot as plt
import shapely
shapely.speedups.disable()
## List input raster files
#raster_path = 'D:\\\\Documenti_Lavoro\\\\PRISMA\\\\data from CNR\\\\PRISMA images\\\\PRS_L2D_STD_20200731101044_20200731101048_0001\\\\PRS_L2D_STD_20200731101044_20200731101048_0001.he5'
cwd = os.getcwd()
raster_path = cwd + os.path.sep + 'PRISMA images' + os.path.sep + 'PRS_L2D_STD_20200731101044_20200731101048_0001' + os.path.sep + 'PRS_L2D_STD_20200731101044_20200731101048_0001.he5'
## Open HDF file
hdflayer = gdal.Open(raster_path, gdal.GA_ReadOnly)
# Get the file metadata
metadata = hdflayer.GetMetadata()
print('Printing all the PRISMA metadata...\\n')
print(metadata)
# List of the datasets within the file
datasets_list = hdflayer.GetSubDatasets()
#print('\\n\\n'.join(map(str, datasets_list)))
# Extract the bands information for the VNIR
SWIR = datasets_list[0][0]
VNIR = datasets_list[2][0]
bands_SWIR = gdal.Open(SWIR, gdal.GA_ReadOnly)
bands_VNIR = gdal.Open(VNIR, gdal.GA_ReadOnly)
VNIR_array = bands_VNIR.ReadAsArray()[:,3:,:] # deleting the all-zero elements
SWIR_array = bands_SWIR.ReadAsArray()[:,:-2,:] # deleting the all-zero elements
band_array = bands_VNIR.ReadAsArray()
VNIR = band_array
VNIR_cube = band_array #np.array(VNIR)
print('Dimensions of the VNIR datacube:',VNIR_cube.shape)
red = VNIR[:,35,:] # 36=632.13165 nm, 35=641.33325 nm
green = VNIR[:,45,:] # 48=530.66705 nm, 45=554.5646 nm
blue = VNIR[:,57,:] # 463.731 nm
IM = np.array([red,green,blue])#.reshape(1181,1203,3)
w,h = IM.shape[1],IM.shape[2]
print('Dimensions of the image:', w,h)
IM = IM.reshape(3,w,h)
print('Dimensions of the pre-processed RGB image:',IM.shape)
t=(w,h,3)
A=np.zeros(t,dtype=np.uint16)
for i in range(w):
for j in range(h):
A[i,j]=[red[i,j],green[i,j],blue[i,j]]
print('Dimensions of the post-processed RGB image:',A.shape)
# initialize the figure
fig,ax = plt.subplots(figsize = (15,15))
# load lats and longs of the PRISMA image
lat = f['HDFEOS/SWATHS/PRS_L2D_HCO/Geolocation Fields/Latitude'][:]
lon = f['HDFEOS/SWATHS/PRS_L2D_HCO/Geolocation Fields/Longitude'][:]
# Define lats and longs for the figure
lons_fig = [6, 19]
lats_fig = [36.3, 47.3]
lat_0 = np.mean(lats_fig)
lon_0 = np.mean(lons_fig)
# initialize the map
map_kwargs = dict(projection='merc', resolution='h',
llcrnrlat=np.min(lats_fig), urcrnrlat=np.max(lats_fig),
llcrnrlon=np.min(lons_fig), urcrnrlon=np.max(lons_fig),
lat_0=lat_0, lon_0=lon_0)
m = Basemap(**map_kwargs)
# drawing parallels and meridians
m.drawparallels(np.arange(np.min(lats_fig),np.max(lats_fig),0.2*(np.max(lats_fig)-np.min(lats_fig))),labels=[1,0,0,0],
color=[0.1,0.1,0.1], fontsize=30, rotation=30,fmt='%8.5g')
m.drawmeridians(np.arange(np.min(lons_fig),np.max(lons_fig),0.2*(np.max(lons_fig)-np.min(lons_fig))),labels=[0,0,0,1],
color=[0.1,0.1,0.1], fontsize=30, rotation=30, fmt='%8.5g')
m.readshapefile(cwd + os.path.sep + 'Italy_shapefile'+ os.path.sep +'Limiti01012018_g'+ os.path.sep +'Reg01012018_g'+ os.path.sep +'Reg01012018_g_WGS84_EPSG4326',
'shapefile_EPSG4326', drawbounds = True, linewidth=1)
patches = []
for info,shape in zip(m.shapefile_EPSG4326_info,m.shapefile_EPSG4326):
if info['DEN_REG']== 'Toscana':
patches.append( Polygon(np.array(shape), True) )
ax.add_collection(PatchCollection(patches, facecolor= 'y', edgecolor='k', linewidths=1., zorder=2))
m.drawcoastlines(linewidth=3)
m.drawcountries(linewidth=2)
m.etopo()
# Labels on axes
#plt.xlabel('Longitude (degree)', labelpad=80, fontsize=16)
#plt.ylabel('Latitude (degree)', labelpad=100, fontsize=16)
plt.annotate('ITALY', xy=(0.3333, 0.5), xycoords='axes fraction', fontsize=80, color='black', fontweight='bold')
plt.show()
C:\\Users\\dario\\anaconda3\\lib\\site-packages\\ipykernel_launcher.py:19: MatplotlibDeprecationWarning:
The dedent function was deprecated in Matplotlib 3.1 and will be removed in 3.3. Use inspect.cleandoc instead.
C:\\Users\\dario\\anaconda3\\lib\\site-packages\\ipykernel_launcher.py:28: MatplotlibDeprecationWarning:
The dedent function was deprecated in Matplotlib 3.1 and will be removed in 3.3. Use inspect.cleandoc instead.
C:\\Users\\dario\\anaconda3\\lib\\site-packages\\ipykernel_launcher.py:39: MatplotlibDeprecationWarning:
The dedent function was deprecated in Matplotlib 3.1 and will be removed in 3.3. Use inspect.cleandoc instead.
# initialize the figure
fig,ax = plt.subplots(figsize = (15,15))
# load lats and longs of the PRISMA image
lat = f['HDFEOS/SWATHS/PRS_L2D_HCO/Geolocation Fields/Latitude'][:]
lon = f['HDFEOS/SWATHS/PRS_L2D_HCO/Geolocation Fields/Longitude'][:]
# Define lats and longs for the figure
lons_fig = [9.6, 12.5]
lats_fig = [42.3, 44.5]
lat_0 = np.mean(lats_fig)
lon_0 = np.mean(lons_fig)
# initialize the map
map_kwargs = dict(projection='merc', resolution='f',
llcrnrlat=np.min(lats_fig), urcrnrlat=np.max(lats_fig),
llcrnrlon=np.min(lons_fig), urcrnrlon=np.max(lons_fig),
lat_0=lat_0, lon_0=lon_0)
m = Basemap(**map_kwargs)
# drawing parallels and meridians
m.drawparallels(np.arange(np.min(lats_fig),np.max(lats_fig),0.2*(np.max(lats_fig)-np.min(lats_fig))),labels=[1,0,0,0],
color=[0.1,0.1,0.1], fontsize=30, rotation=30, fmt='%8.5g')
m.drawmeridians(np.arange(np.min(lons_fig),np.max(lons_fig),0.2*(np.max(lons_fig)-np.min(lons_fig))),labels=[0,0,0,1],
color=[0.1,0.1,0.1], fontsize=30, rotation=30, fmt='%8.5g')
m.readshapefile(cwd + os.path.sep + 'Italy_shapefile'+ os.path.sep +'Limiti01012018_g'+ os.path.sep +'Reg01012018_g'+ os.path.sep +'Reg01012018_g_WGS84_EPSG4326',
'shapefile_EPSG4326', drawbounds = True, linewidth=1)
patches = []
for info,shape in zip(m.shapefile_EPSG4326_info,m.shapefile_EPSG4326):
if info['DEN_REG']== 'Toscana':
x, y = zip(*shape)
m.plot(x, y, marker=None,color='y',linewidth=5)
m.drawcoastlines(linewidth=3)
m.drawcountries(linewidth=2)
m.etopo()
# drawing the PRISMA image
mesh_rgb = A[:, :-1, :]/np.max(A) # also A[:, 1:, :] works fine
colorTuple = mesh_rgb.reshape((mesh_rgb.shape[0] * mesh_rgb.shape[1]), 3)
alpha = 1.0
colorTuple = np.insert(colorTuple,3,alpha,axis=1)
## What you put in for the image doesn't matter because of the color mapping
eps_lon = -0.001 # additive offset in degree
eps_lat = -0.0012 # additive offset in degree
m.pcolormesh(lon+eps_lon, lat+eps_lat, A[:,:,0], latlon=True, color=colorTuple)
plt.annotate('TUSCANY', xy=(0.3333, 0.5), xycoords='axes fraction', fontsize=80, color='black', fontweight='bold')
# Labels on axes
#plt.xlabel('Longitude (degree)', labelpad=80, fontsize=16)
#plt.ylabel('Latitude (degree)', labelpad=100, fontsize=16)
# Showing image
plt.show()
C:\\Users\\dario\\anaconda3\\lib\\site-packages\\ipykernel_launcher.py:19: MatplotlibDeprecationWarning:
The dedent function was deprecated in Matplotlib 3.1 and will be removed in 3.3. Use inspect.cleandoc instead.
C:\\Users\\dario\\anaconda3\\lib\\site-packages\\ipykernel_launcher.py:28: MatplotlibDeprecationWarning:
The dedent function was deprecated in Matplotlib 3.1 and will be removed in 3.3. Use inspect.cleandoc instead.
C:\\Users\\dario\\anaconda3\\lib\\site-packages\\ipykernel_launcher.py:38: MatplotlibDeprecationWarning:
The dedent function was deprecated in Matplotlib 3.1 and will be removed in 3.3. Use inspect.cleandoc instead.
from mpl_toolkits.basemap import Basemap
import matplotlib.patches as mpatches
# initialize the figure
fig,ax = plt.subplots(figsize = (16,16))
# load lats and longs of the PRISMA image
lat = f['HDFEOS/SWATHS/PRS_L2D_HCO/Geolocation Fields/Latitude'][:]
lon = f['HDFEOS/SWATHS/PRS_L2D_HCO/Geolocation Fields/Longitude'][:]
# Define lats and longs for the figure
eps_lon = -0.001 # additive offset in degree
eps_lat = -0.0012 # additive offset in degree
lons_fig = [np.min(lon+eps_lon), np.max(lon+eps_lon)]
lats_fig = [np.min(lat+eps_lat), np.max(lat+eps_lat)]
lat_0 = np.mean(lats_fig)
lon_0 = np.mean(lons_fig)
# initialize the map
map_kwargs = dict(projection='merc', resolution='l',
llcrnrlat=np.min(lats_fig), urcrnrlat=np.max(lats_fig),
llcrnrlon=np.min(lons_fig), urcrnrlon=np.max(lons_fig),
lat_0=lat_0, lon_0=lon_0)
m = Basemap(**map_kwargs)
# drawing parallels and meridians
m.drawparallels(np.arange(np.min(lats_fig),np.max(lats_fig),0.2*(np.max(lats_fig)-np.min(lats_fig))),labels=[1,0,0,0],
color=[0.6,0.6,0.6], fontsize=30, rotation=30, fmt='%8.5g')
m.drawmeridians(np.arange(np.min(lons_fig),np.max(lons_fig),0.2*(np.max(lons_fig)-np.min(lons_fig))),labels=[0,0,0,1],
color=[0.6,0.6,0.6], fontsize=30, rotation=30, fmt='%8.5g')
m.etopo()
# drawing the PRISMA image
mesh_rgb = A[:, :-1, :]/np.max(A) # also A[:, 1:, :] works fine
colorTuple = mesh_rgb.reshape((mesh_rgb.shape[0] * mesh_rgb.shape[1]), 3)
alpha = 1.0
colorTuple = np.insert(colorTuple,3,alpha,axis=1)
## What you put in for the image doesn't matter because of the color mapping
m.pcolormesh(lon+eps_lon, lat+eps_lat, A[:,:,0], latlon=True, color=colorTuple)
# Labels on axes
#plt.xlabel('Longitude (degree)', labelpad=80, fontsize=16)
#plt.ylabel('Latitude (degree)', labelpad=100, fontsize=16)
# Showing image
plt.show()
from mpl_toolkits.basemap import Basemap
import matplotlib.patches as mpatches
# initialize the figure
fig,ax = plt.subplots(figsize = (15,15))
# load lats and longs of the PRISMA image
lat = f['HDFEOS/SWATHS/PRS_L2D_HCO/Geolocation Fields/Latitude'][:]
lon = f['HDFEOS/SWATHS/PRS_L2D_HCO/Geolocation Fields/Longitude'][:]
# Define lats and longs for the figure
lons_fig = [11.016, 11.100]
lats_fig = [42.814, 42.886]
lat_0 = np.mean(lats_fig)
lon_0 = np.mean(lons_fig)
# initialize the map
map_kwargs = dict(projection='merc', resolution='l',
llcrnrlat=np.min(lats_fig), urcrnrlat=np.max(lats_fig),
llcrnrlon=np.min(lons_fig), urcrnrlon=np.max(lons_fig),
lat_0=lat_0, lon_0=lon_0)
m = Basemap(**map_kwargs)
# drawing parallels and meridians
m.drawparallels(np.arange(np.min(lats_fig),np.max(lats_fig),0.2*(np.max(lats_fig)-np.min(lats_fig))),labels=[1,0,0,0],
color=[0.6,0.6,0.6], fontsize=30, rotation=30, fmt='%8.5g')
m.drawmeridians(np.arange(np.min(lons_fig),np.max(lons_fig),0.2*(np.max(lons_fig)-np.min(lons_fig))),labels=[0,0,0,1],
color=[0.6,0.6,0.6], fontsize=30, rotation=30, fmt='%8.5g')
# drawing the polygons in the shapefile
m.readshapefile(cwd + os.path.sep + 'acquisitions'+ os.path.sep +'shapefile_EPSG4326','shapefile_EPSG4326',
drawbounds = False)
for info,shape in zip(m.shapefile_EPSG4326_info,m.shapefile_EPSG4326):
if info['crop_type']== 'corn':
line_color = 'm'
elif info['crop_type']== 'tomato':
line_color = 'y'
x, y = zip(*shape)
m.plot(x, y, marker=None, color=line_color, linewidth=6)
# drawing the PRISMA image
mesh_rgb = A[:, :-1, :]/np.max(A) # also A[:, 1:, :] works fine
colorTuple = mesh_rgb.reshape((mesh_rgb.shape[0] * mesh_rgb.shape[1]), 3)
alpha = 1.0
colorTuple = np.insert(colorTuple,3,alpha,axis=1)
## What you put in for the image doesn't matter because of the color mapping
eps_lon = -0.001 # additive offset in degree
eps_lat = -0.0012 # additive offset in degree
m.pcolormesh(lon+eps_lon, lat+eps_lat, A[:,:,0], latlon=True, color=colorTuple)
# Labels on axes
#plt.xlabel('Longitude (degree)', labelpad=80, fontsize=16)
#plt.ylabel('Latitude (degree)', labelpad=100, fontsize=16)
# polygons legend
corn_fields = mpatches.Patch(color='m', label='Corn fields')
tomato_fields = mpatches.Patch(color='y', label='Tomato fields')
plt.legend(handles=[corn_fields,tomato_fields], fontsize=40)
# Showing image
plt.show()
C:\\Users\\dario\\anaconda3\\lib\\site-packages\\ipykernel_launcher.py:22: MatplotlibDeprecationWarning:
The dedent function was deprecated in Matplotlib 3.1 and will be removed in 3.3. Use inspect.cleandoc instead.
C:\\Users\\dario\\anaconda3\\lib\\site-packages\\ipykernel_launcher.py:32: MatplotlibDeprecationWarning:
The dedent function was deprecated in Matplotlib 3.1 and will be removed in 3.3. Use inspect.cleandoc instead.
C:\\Users\\dario\\anaconda3\\lib\\site-packages\\IPython\\core\\pylabtools.py:132: UserWarning: Creating legend with loc="best" can be slow with large amounts of data.
fig.canvas.print_figure(bytes_io, **kw)
from shapely.geometry import Point, Polygon
lat = f['HDFEOS/SWATHS/PRS_L2D_HCO/Geolocation Fields/Latitude'][:]
lon = f['HDFEOS/SWATHS/PRS_L2D_HCO/Geolocation Fields/Longitude'][:]
eps_lon = -0.001 # additive offset in degree
eps_lat = -0.0012 # additive offset in degree
lon_corrected = lon + eps_lon
lat_corrected = lat + eps_lat
pixels_in_fields = []
for item,shp in enumerate(fields_shp.iterrows()):
poly = Polygon(shp[1].geometry)
crop_type = shp[1].crop_type
origin = shp[1].origin
pixels_in_fields.append({'id':item,'crop_type':crop_type,'origin':origin,'pixels':[]})
print(pixels_in_fields[item])
for i in range(lon_corrected.shape[0]):
for j in range(lon_corrected.shape[1]):
p = Point(lon_corrected[i,j],lat_corrected[i,j])
if p.within(poly):
pixels_in_fields[item]['pixels'].append(DATA_CUBE[i,:,j].T)