2

I am trying to manipulate bad pixel values in a raster by using the Con-Statement via ArcPy. Using the build-in Map Algebra function "Raster Calculator", the results are good. To transfer the work flow to a script, the outcome is different. The pixel values should be between [-1;1].

arcpy.env.workspace = out_folder #path to my folder containing the raster files
list = arcpy.ListFiles('*.tif')
for ras in list:
     outras1 = Con(ras > 1, 1, ras)
     outras2 = Con(outras1 < -1, -1, outras1)
     outras2.save(ras + '_mod.tif') 

Can you tell, what I am doing wrong?

The results show only pixel values of 1. Additional information: I have large areas of NoData values in my raster.

4
  • Otherwise, the combination of the Con statement: outras1 = Con(ras > 1, 1, Con(ras < -1.0,-1.0, ras)) produces the same result.
    – Andi90
    Commented Nov 9, 2017 at 13:26
  • 1
    Try r=arcpy.Raster(ras), because this will create raster from string.
    – FelixIP
    Commented Nov 9, 2017 at 19:06
  • Thankyou for the "object" reference to this process. I am converting pixels with multiple elevation values to the maximum elevation found for hundreds of polygon segments that cross over culverts. Sample code. rasterlist = arcpy.ListRasters(raspref+"*") print "rasterlist= ",rasterlist for i in rasterlist: inputraster = i print "inputraster = ",inputraster print "Getting MAXIMUM elevation value in DEM" raster = arcpy.GetRasterProperties_management (inputraster, "MAXIMUM") elevMax = float(raster.getOutput(0)) print "MAXIMUM elevation for", inputraster, "= ", elevMax rast = arcpy.Raster(inputrast
    – MRichey
    Commented Nov 21, 2017 at 18:28
  • This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
    – Dan C
    Commented Dec 12, 2017 at 17:24

1 Answer 1

3

@FelixIP comment is correct, you need to convert your raster file to a raster object using arcpy.Raster() before using Con().

Here is the code that worked for me:

import arcpy
from arcpy.sa import *
from arcpy import env

env.workspace = r"F:\Test\Test\FolderName"

ext_out = arcpy.CheckOutExtension("SPATIAL")

raslist = arcpy.ListRasters('*.tif')

for ras in raslist:
    raster = arcpy.Raster(ras)

    ras_con = Con(raster < -1, -1, Con(raster > 1, 1,raster))
    ras_con.save(ras[:-4]+"_Final.tif")
1
  • 1
    This post is way more informative than any of the official Esri documentation I've read on using the raster calculator in Python. Thank you! Commented Oct 18, 2022 at 22:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.