Advertisement
Abhisek92

Image_Lowess.py

Mar 17th, 2024 (edited)
630
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.89 KB | None | 0 0
  1. import numpy as np
  2. import rasterio as rio
  3. from functools import partial
  4. from statsmodels.nonparametric.smoothers_lowess import lowess
  5.  
  6.  
  7. partial_lowess = partial(
  8.     lowess,
  9.     frac=2/3,
  10.     it=3,
  11.     delta=0.0,
  12.     xvals=None,
  13.     is_sorted=False,
  14.     missing='drop',
  15.     return_sorted=True
  16. )
  17.  
  18. apply_lowess = np.vectorize(partial_lowess, signature="(m),(m)->(m, 2)")
  19.  
  20. with rio.open("ascat_raw_mask.tif") as ascat_src, rio.open("fac_ais_mask.tif") as fac_src:
  21.     assert ascat_src.crs == fac_src.crs, "CRS mismatch!"
  22.     ascat_data = ascat_src.read(masked=True)
  23.     fac_data = fac_src.read(masked=True)
  24.     ascat_backward = np.array(~ascat_src.transform).reshape((3, 3))
  25.     fac_forward = np.array(fac_src.transform).reshape((3, 3))
  26.  
  27.     ascat_mask = np.any(ascat_data.mask, axis=0)
  28.     fac_mask = np.any(fac_data.mask, axis=0)
  29.  
  30.     fac_row, fac_col = np.where(~fac_mask)
  31.     fac_indexes = np.stack(
  32.         [(fac_col + 0.5), (fac_row + 0.5), np.ones_like(fac_col)],
  33.         axis=-1
  34.     )
  35.     ascat_indexes = np.round(
  36.         (
  37.             np.einsum(
  38.                 "ij,kj -> ki", ascat_backward, np.einsum(
  39.                     "ij,kj -> ki", fac_forward, fac_indexes
  40.                 )
  41.             )[:, :-1] - 0.5
  42.         ),
  43.         decimals=0
  44.     ).astype(int)
  45.     ascat_col, ascat_row = np.array_split(
  46.         ary=ascat_indexes,
  47.         indices_or_sections=ascat_indexes.shape[-1],
  48.         axis=-1
  49.     )
  50.    
  51.     ascat_col = np.squeeze(a=ascat_col, axis=-1)
  52.     ascat_row = np.squeeze(a=ascat_row, axis=-1)
  53.  
  54.     indices = ~ascat_mask[ascat_row, ascat_col]
  55.     ascat_col = ascat_col[indices]
  56.     ascat_row = ascat_row[indices]
  57.     fac_row = fac_row[indices]
  58.     fac_col = fac_col[indices]
  59.  
  60.     ascat_values = ascat_data[:, ascat_row, ascat_col].filled()
  61.     fac_values = fac_data[:, fac_row, fac_col].filled()
  62.     smooth = apply_lowess(ascat_values.T, fac_values.T)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement