Last active
October 6, 2020 19:38
-
-
Save giswqs/eb98b1203a50ae1079bead62f655d4a7 to your computer and use it in GitHub Desktop.
County_field_boundary .ipynb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"cells": [ | |
{ | |
"metadata": { | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "import ee\nimport geemap\n\nMap = geemap.Map()\n\n# IDENTIFY FIELDS FOR PREDICTION\n#---DEFINE FUNCTIONS-------------------------------#\n# create binary layer for if crop is soybean\ndef isSoy(image):\n return image.eq(5)\n\n# create binary layer for if field had soybean in last 10 years\ndef soyField(imageColl, countyGeom):\n # create binary layer if soy\n historicalCrops = imageColl.map(isSoy)\n # sum over all years\n soyFields = historicalCrops.sum()\n # create mask for fields planted at least 1 year of soy over past 10 years\n mask = soyFields.gt(0)\n # update CDL image with soy mask and crop to county\n soyMask = soyFields.updateMask(mask).clip(counties.geometry())\n return(soyMask)\n\n#----DEFINE REGION OF INTEREST--------------------------------------#\n# define counties of interest\ncountyList = ['Dade']\n# load state boundary collection\ncounties = ee.FeatureCollection(\"TIGER/2018/Counties\") \\\n .filter(ee.Filter.inList('NAME', countyList))\n#-------CREATE SOYBEAN FIELD LAYER----------------------------#\n# load cropland data layer from previous 10 years\nhistoricalCrops = ee.ImageCollection('USDA/NASS/CDL') \\\n .filter(ee.Filter.date('2010-01-01', '2019-12-31')) \\\n .select('cropland') \\\n .filterBounds(counties.geometry())\nsoyMap = soyField(historicalCrops, counties)\n#Map.addLayer(ndviCounty, {min: 0, max:1, palette: ['blue', 'white', 'green'], opacity: .5}, 'ndvi')\nMap.addLayer(soyMap, {'palette': [\"B997C7\"], 'opacity': .5}, 'SoyFields')\n# Export the image, specifying scale and region.\n#soyMap_Int = ee.Image.toInt(soyMap)\n\n######################################################\n#Here below is what is added on top of Rebecca's code\n######################################################\n#/ Unsupervised classification based on training dataset using the county bounary --- for post-processing the soyMap raster layer\nseeds = ee.Algorithms.Image.Segmentation.seedGrid(36)\n#Map.addLayer(seeds.mask(seeds), {}, 'seeds')\n\n# training region is the full county \"soyMap\" image\ntraining = soyMap.sample(**{\n 'region': counties,\n 'scale': 30,\n 'numPixels': 5000\n})\n\n# train cluster on a county image\nsoyMap_clusterer = ee.Clusterer.wekaKMeans(10).train(training)\n# cluster the complete county image\nsoyMap_cluster_result = soyMap.cluster(soyMap_clusterer)\n\nMap.addLayer(soyMap_cluster_result.randomVisualizer(), {}, 'soyMap_cluster_result')\n\n# define the size of a low-pass kernel\nkernel_size = ee.Kernel.square(**{\n 'radius': 3, 'units': 'pixels', 'normalize': True\n})\n\n# Smooth the image by convolving with the low-pass-kernel\nsoyMap_cluster_result_smooth = soyMap_cluster_result.convolve(kernel_size)\nMap.addLayer(soyMap_cluster_result_smooth, {}, 'soyMap_cluster_result_smooth')\n#---------------------------------------------------------------------------------------------------\n# perform impervious layers [using NLCD C21, C22, C23 and C24] masking\n#---------------------------------------------------------------------------------------------------\nnlcd = ee.ImageCollection('USGS/NLCD') \\\n .filter(ee.Filter.eq('system:index', 'NLCD2016')) \\\n .select(0) \n\n# Map-out developed open space (C21), developed -- low (C22), medium (C23) and high (C24) intensities\n\ndef func_jnl(image):\n return image.remap([21,22,23,24],\n [0, 0, 0, 0], 1)\n\nnlcdImperv = nlcd.map(func_jnl)\n\n#print(nlcd.first())\n#print(nlcdImperv.first())\nMap.addLayer(nlcdImperv, {}, 'nlcd_impervLayer')\nnlcd_test = nlcdImperv. filterBounds(counties.geometry())\n#Map.addLayer(nlcd_test, {}, 'nlcd_test')\n\ndef isImperv(image):\n return image.eq(1)\n\n#---------------------------------------------------------------------------------------------------\n#/ Export final output as either a raster or a vector (.shp or .GeoJSON) file format\n#---------------------------------------------------------------------------------------------------\n# Convert the raster data type to integer\nsoyMap_result_smooth_Int = soyMap_cluster_result_smooth.toInt()\nMap.addLayer(soyMap_result_smooth_Int, {}, 'soyMap_result_smooth_Int')\n\n# Export as a raster format\n# Export.image.toCloudStorage({\n# 'image': soyMap_result_smooth_Int,\n# 'description': 'soyMap_result_smooth_Int',\n# 'scale': 30,\n# #region: 'counties',\n# 'fileFormat': 'GeoTIFF',\n# 'bucket': 'gee-eval'\n\n# })\n#print(soyMap_result_smooth_Int)\n\n# Convert raster to vector\n#clusterValue = maskUrban.select('cluster')\nsoyMap_result_smooth_Int_vector = soyMap_result_smooth_Int.reduceToVectors(**{\n 'reducer': ee.Reducer.countEvery(),\n 'geometry': counties,\n 'scale': 30,\n 'maxPixels': 1e8\n})\nsoyMap_result_smooth_Int_vector2 = ee.FeatureCollection(soyMap_result_smooth_Int_vector)\nMap.addLayer(soyMap_result_smooth_Int_vector2.union(1), {},'soyMap_result_smooth_Int_vector2')\n\n# Export the vector data\n# Export.table.toCloudStorage({\n# 'collection': soyMap_result_smooth_Int_vector2.union(1),\n# 'description': 'county_soyFields_final',\n# #fileFormat: 'SHP',\n# 'fileFormat': 'GeoJSON',\n# 'bucket': 'gee-eval'\n# })\n##################################################\n##################################################\nMap\n", | |
"execution_count": 7, | |
"outputs": [ | |
{ | |
"output_type": "display_data", | |
"data": { | |
"text/plain": "Map(center=[40, -100], controls=(WidgetControl(options=['position'], widget=HBox(children=(ToggleButton(value=…", | |
"application/vnd.jupyter.widget-view+json": { | |
"version_major": 2, | |
"version_minor": 0, | |
"model_id": "e9d3b8e961ac4aba947ce2a63847e3c5" | |
} | |
}, | |
"metadata": {} | |
} | |
] | |
}, | |
{ | |
"metadata": { | |
"trusted": false | |
}, | |
"cell_type": "code", | |
"source": "", | |
"execution_count": null, | |
"outputs": [] | |
} | |
], | |
"metadata": { | |
"kernelspec": { | |
"name": "python3", | |
"display_name": "Python 3", | |
"language": "python" | |
}, | |
"language_info": { | |
"name": "python", | |
"version": "3.8.2", | |
"mimetype": "text/x-python", | |
"codemirror_mode": { | |
"name": "ipython", | |
"version": 3 | |
}, | |
"pygments_lexer": "ipython3", | |
"nbconvert_exporter": "python", | |
"file_extension": ".py" | |
}, | |
"varInspector": { | |
"window_display": false, | |
"cols": { | |
"lenName": 16, | |
"lenType": 16, | |
"lenVar": 40 | |
}, | |
"kernels_config": { | |
"python": { | |
"library": "var_list.py", | |
"delete_cmd_prefix": "del ", | |
"delete_cmd_postfix": "", | |
"varRefreshCmd": "print(var_dic_list())" | |
}, | |
"r": { | |
"library": "var_list.r", | |
"delete_cmd_prefix": "rm(", | |
"delete_cmd_postfix": ") ", | |
"varRefreshCmd": "cat(var_dic_list()) " | |
} | |
}, | |
"types_to_exclude": [ | |
"module", | |
"function", | |
"builtin_function_or_method", | |
"instance", | |
"_Feature" | |
] | |
}, | |
"hide_input": false, | |
"toc": { | |
"nav_menu": {}, | |
"number_sections": true, | |
"sideBar": true, | |
"skip_h1_title": true, | |
"base_numbering": 1, | |
"title_cell": "Table of Contents", | |
"title_sidebar": "Table of Contents", | |
"toc_cell": false, | |
"toc_position": {}, | |
"toc_section_display": true, | |
"toc_window_display": true | |
}, | |
"gist": { | |
"id": "eb98b1203a50ae1079bead62f655d4a7", | |
"data": { | |
"description": "County_field_boundary .ipynb", | |
"public": true | |
} | |
}, | |
"_draft": { | |
"nbviewer_url": "https://gist.github.com/eb98b1203a50ae1079bead62f655d4a7" | |
} | |
}, | |
"nbformat": 4, | |
"nbformat_minor": 4 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment