{"cells":[{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"a3acf673-fdce-78a4-f470-d3f98b72de7c"},"outputs":[],"source":"\n\"\"\"\nThis Scritp Show Traning Polygons on Satalite İmages for each Class\n\"\"\"\n\n\n\n#Import Libraries\nimport os,cv2,tifffile\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom shapely import wkt, affinity\n\n\n\n\"\"\"\nClasses \n        'Buildings'        :1,\n        'Structures '      :2,\n        'Road'             :3,\n        'Track'            :4,\n        'Trees'            :5,\n        'Crops'            :6,\n        'Waterway'         :7,\n        'StandingWater'    :8,\n        'VehicleLarge'     :9,\n        'VehicleSmall'     :10,\n\"\"\"\n\n#Select a class and image id to be drawn\nClass = 4\nImageID = '6120_2_2' #'6120_2_2', '6100_1_3', '6140_3_1','6110_3_1','6100_2_3','6140_1_2','6120_2_0','6100_2_2','6110_1_2','6070_2_3','6110_4_0','6090_2_0','6060_2_3'\n#---------------------------------------\n\n#Define Functions\ndef stretch2(band, lower_percent=2, higher_percent=98):\n    a = 0 #np.min(band)\n    b = 255  #np.max(band)\n    c = np.percentile(band, lower_percent)\n    d = np.percentile(band, higher_percent)        \n    out = a + (band - c) * (b - a) / (d - c)    \n    out[out<a] = a\n    out[out>b] = b\n    return out\ndef adjust_contrast(x):    \n    for i in range(3):\n        x[:,:,i] = stretch2(x[:,:,i])\n    return x.astype(np.uint8)  \ndef truth_polys(image_id, class_id, W, H):\n    x = pd.read_csv('../input/train_wkt_v4.csv')\n    rows = x.loc[(x.ImageId==image_id) & (x.ClassType==class_id), 'MultipolygonWKT']\n    mp = wkt.loads(rows.values[0])\n    grid_sizes = pd.read_csv('../input/grid_sizes.csv', names=['ImageId', 'Xmax', 'Ymin'], skiprows=1)\n    xmax, ymin = grid_sizes[grid_sizes.ImageId == ImageID].iloc[0,1:].astype(float)    \n    W_ = W * (W/(W+1.))\n    H_ = H * (H/(H+1.))\n    x_scaler = W_ / xmax\n    y_scaler = H_ / ymin\n    return affinity.scale(mp, xfact = x_scaler, yfact= y_scaler, origin=(0,0,0))  \n#-----------------------------------------------------------------------------------------    \n\n\n#Read threeband image\nrgbfile=os.path.join('..', 'input', 'three_band', '{}.tif'.format(ImageID))              \nrgb = tifffile.imread(rgbfile)\nrgb = np.rollaxis(rgb, 0, 3)     \n\n#Read 16band m image\nmfile = os.path.join('..', 'input', 'sixteen_band', '{}_M.tif'.format(ImageID))\nimg_m = tifffile.imread(mfile)    \nimg_m = np.rollaxis(img_m, 0, 3)\nimg_m = cv2.resize(img_m, tuple(reversed(rgb.shape[:2])))    \n \n#Turn m image into rgb color           \nx = np.zeros_like(rgb)\nx[:,:,0] = img_m[:,:,4]\nx[:,:,1] = img_m[:,:,2]\nx[:,:,2] = img_m[:,:,1]\nx = adjust_contrast(x).copy()\n\nH=len(x); W=len(x[0])\n#Read Polygons\npolys = truth_polys(ImageID, Class,W,H)\n\n#Add polygons to the x image --Edit: 01.25.17  included hole verteces in polygons \n#patches=[]\nint_vertices=lambda x: np.array(x).round().astype(np.int32)\nfor poly_id, poly in enumerate(polys):\n    #x1,y1,x2,y2 = [int(pb) for pb in poly.bounds]\n    xys=int_vertices(poly.exterior.coords) \n    cv2.polylines(x,[xys],True,(255,0,0),3)\n    for pi in poly.interiors:\n        ixys=int_vertices(pi.coords)\n        cv2.polylines(x,[ixys],True,(255,0,0),3)\n    #patches.append(np.hstack([x[y1-PADDING:y2+PADDING, x1-PADDING:x2+PADDING,:]]))\n\n##To focus on each element\n#PADDING = 10\n#W = 3396\n#H = 3348\n#patches = []\n#titles = []            \n#for poly_id, poly in enumerate(polys):\n#    x1,y1,x2,y2 = [int(pb) for pb in poly.bounds]\n#    cv2.rectangle(x, (x1,y1), (x2,y2), (255,0,0), 1)\n#    cv2.rectangle(img_p, (x1,y1), (x2,y2), (255,0,0), 1)\n#    patches.append(np.hstack([x[y1-PADDING:y2+PADDING, x1-PADDING:x2+PADDING,:], img_p[y1-PADDING:y2+PADDING, x1-PADDING:x2+PADDING,:]]))\n#    titles.append(\"ImageID: {} -- poly_id: {}\".format(ImageID, poly_id))\n#\n\n\n#-----------------------------------------------------------------------------------------    \n#Plot\nfig, ax = plt.subplots(figsize=(9,9))\nax.imshow(x)\nplt.savefig(ImageID+\".png\")\n\n#fig, ax = plt.subplots(1, 1, figsize=(10,10))\n#for i in range(10):\n#    ax.imshow(patches[i]) "}],"metadata":{"_change_revision":0,"_is_fork":false,"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.6.0"}},"nbformat":4,"nbformat_minor":0}