Advertisement
Abhisek92

data_prep

Jan 27th, 2020
349
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.09 KB | None | 0 0
  1. import numpy as np
  2. import pandas as pd
  3. import json
  4. from shapely import geometry
  5. from pathlib import Path
  6. import rasterio as rio
  7.  
  8. shape_fpath = Path("/home/abhisek/Documents/train/via_region_data.json")
  9. aoi_df = pd.DataFrame(columns=('FileName', 'Polygon', 'ClassName'))
  10. with open(shape_fpath) as json_file:
  11.     annotations = json.load(json_file)
  12.     for fkey in annotations.keys():
  13.         fregions = annotations[fkey]['regions']
  14.         if isinstance(fregions, list):
  15.             labeled_aois = [
  16.                 (
  17.                     fkey,
  18.                     geometry.Polygon(
  19.                         list(
  20.                             zip(
  21.                                 r['shape_attributes']['all_points_x'],
  22.                                 r['shape_attributes']['all_points_y']
  23.                             )
  24.                         )
  25.                     ),
  26.                     list(r['region_attributes']['name'].keys())[0]
  27.                 )
  28.                 for r in fregions
  29.             ]
  30.             fdf = pd.DataFrame(labeled_aois, columns=('FileName', 'Polygon', 'ClassName'))
  31.             aoi_df = pd.concat((aoi_df, fdf), ignore_index=True)
  32.  
  33. u_class = set(aoi_df['ClassName'].tolist())
  34. u_files = set(aoi_df['FileName'].tolist())
  35.  
  36. label_map = {'nodata': 0}
  37. l = 1
  38. for c in u_class:
  39.     label_map[c] = l
  40.     l += 1
  41.    
  42.    
  43.     def pixel_check(x, y, a_polygon, true_val=True, false_val=False):
  44.         if a_polygon.contains(geometry.Point(x, y)):
  45.             return true_val
  46.         else:
  47.             return false_val
  48.     image_check = np.vectorize(pixel_check, excluded=['a_polygon', 'true_val', 'false_val'])
  49.     def create_image_mask(a_polygon, class_name, img_shape):
  50.         assert isinstance(img_shape, tuple) and len(img_shape) == 2
  51.         r, c = img_shape
  52.         r_grid, c_grid = np.meshgrid(np.arange(r), np.arange(c))
  53.         image_mask = image_check(
  54.             a_polygon=a_polygon,
  55.             x=r_grid,
  56.             y=c_grid,
  57.             true_val=label_map[class_name],
  58.             false_val=label_map['nodata']
  59.         )
  60.         return image_mask
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement