Iterator for raster to polygon

246
2
11-24-2017 12:05 PM
Highlighted
New Contributor

Hi everyone,

I am trying to convert my raster (.tif) into simple polygon feature classes. I am fairly new to Python and this is the script I though of (which returns no error, but simply no results come from it):

import os
import arcpy
from arcpy.sa import *
from arcpy import env
arcpy.CheckOutExtension("spatial")
env.overwriteOutput=True

rootfolder="r'Z:\bda_7unzip\bda\LANDSAT 5\63_12'"
for root, dirs, files in os.walk(rootfolder):
    for d in dirs:
         NDSI = Raster(rootfolder+os.sep+d+os.sep+d+"_NDSI_tresh0.33.tif")
         arcpy.RasterToPolygon_conversion("NDSI",'rootfolder+os.sep+d+os.sep+d+"_NDSI_tresh0.33"',"SIMPLIFY","Value")

any thought on how I could modify this or new scripting ideas?

Reply
0 Kudos
2 Replies
Highlighted
Esri Esteemed Contributor

I would expect one or several errors to occur with this code. The reason that it doesn't happen is that your "rootfolder" does probably not have any sub folders. If you use os.walk you would normally use the files to get a certain file.

Consider the following example. I have a path "C:\GeoNet\Raster2Polygon" that I specify as the rootfolder and this folder has a single sub folder called myTifFolder:

If I run this code:

import os

rootfolder=r'C:\GeoNet\Raster2Polygon'
for root, dirs, files in os.walk(rootfolder):
    for d in dirs:
        print d
        print rootfolder+os.sep+d+os.sep+d+"_NDSI_tresh0.33.tif"

It will return:

C:\GeoNet\Raster2Polygon\myTifFolder\myTifFolder_NDSI_tresh0.33.tif

Is that what you are after?

If you want to loop through all the .tif files in a folder or sub folder like this situation:

You could use this:

import os

rootfolder=r'C:\GeoNet\Raster2Polygon'
for root, dirs, files in os.walk(rootfolder):
    for file_name in files:
        name, ext = os.path.splitext(file_name)
        if ext.upper() == ".TIF":
            print os.path.join(root, file_name)

This will yield:

C:\GeoNet\Raster2Polygon\myTifFolder\myTif1.tif
C:\GeoNet\Raster2Polygon\myTifFolder\myTif2.tif
C:\GeoNet\Raster2Polygon\myTifFolder\myTif3.tif

There is another thing going on with trying to convert the raster to polygon and this is this part:

arcpy.RasterToPolygon_conversion("NDSI"...

You specify "NDSI" but this is simply a string that contains the text "NDSI" and not a reference to the raster. Skip the quotes to reference the raster.

Reply
0 Kudos
Highlighted
New Contributor

that helped a lot thanks!

Reply
0 Kudos