Abhisek92

Extract Pixels in Polygon

May 29th, 2020
288
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.24 KB | None | 0 0
  1. def extract_pixels(imgfile, shapefile, attributes=None, all_touched=True):
  2.     lbl_flag = False
  3.     with fiona.open(shapefile) as shp_fp:
  4.         with rio.open(imgfile, 'r') as img_fp:
  5.             feature_vectors, label_vectors = list(), list()
  6.             for feature in shp_fp:
  7.                 if feature["geometry"]['type'] in ("MultiPolygon", "Polygon"):
  8.                     masked_box, _ = rio_mask(
  9.                         dataset=img_fp,
  10.                         shapes=[feature["geometry"],],
  11.                         all_touched=all_touched,
  12.                         crop=True,
  13.                         filled=False,
  14.                         pad=False
  15.                     )
  16.                     # RasterIO Reads Bands First
  17.                     bandwise_pixeldump = list()
  18.                     for i in range(masked_box.shape[0]):
  19.                         assert (
  20.                             masked_box[0].mask == masked_box[i].mask
  21.                         ).all(), "Band-wise Mask Mismatch! <Band {}>".format(i)
  22.                         bandwise_pixeldump.append(masked_box[i].compressed())
  23.                     pixel_dump = np.stack(bandwise_pixeldump, axis=-1)
  24.                     if attributes and isinstance(attributes, (str, tuple, list)):
  25.                         if isinstance(attributes, str):
  26.                             attributes = (attributes,)
  27.                         bandwise_labeldump = list()
  28.                         for attr in attributes:
  29.                             assert attr in shp_fp.schema[
  30.                                 'properties'
  31.                             ].keys(), "Provided Attribute({}) not found in data!".format(
  32.                                 attr
  33.                             )
  34.                             lbl_flag = True
  35.                             fill_val = feature['properties'][attr]
  36.                             if np.issubdtype(type(fill_val), np.number):
  37.                                 proxy_array = np.full_like(
  38.                                     bandwise_pixeldump[-1],
  39.                                     fill_val
  40.                                 )
  41.                             else:
  42.                                 proxy_array = np.full_like(
  43.                                     bandwise_pixeldump[-1],
  44.                                     fill_val,
  45.                                     dtype=object
  46.                                 )
  47.                             bandwise_labeldump.append(proxy_array)
  48.                         label_dump = np.stack(bandwise_labeldump, axis=-1)
  49.                         label_vectors.append(label_dump)
  50.                     feature_vectors.append(pixel_dump)
  51.             if len(feature_vectors) > 0:
  52.                 feature_vectors = np.concatenate(feature_vectors, axis=0)
  53.             else:
  54.                 feature_vectors = np.array([])
  55.             if len(label_vectors) > 0:
  56.                 assert len(label_vectors) == len(label_vectors), "Label Vector Count and Feature Vector Count Mismatch!"
  57.                 label_vectors = np.concatenate(label_vectors, axis=0)
  58.             else:
  59.                 label_vectors =  np.array([])
  60.             if lbl_flag:
  61.                 return feature_vectors, label_vectors
  62.             else:
  63.                 return feature_vectors
Add Comment
Please, Sign In to add comment