Count of different pixels in raster

2255
2
05-03-2011 12:17 PM
LukaszB_
New Contributor
Hi,

I'm trying to write a script to count of number different value of pixels in raster. Rasters contain only 0 or 1 value and all are in "Mask" catalog (there are about 200). This script must write it to text file, first name then number of pixels.

Like this : Name of raster   number of pixel 0, number of pixel 1

I wrote the script below:

import arcpy
from arcpy import env
env.workspace = "E:\\Mask"
outfile = open("E:\\RastStats.txt", 'w')
rastlist = arcpy.ListRasters("*", "")
for raster in rastlist:
    arcpy.CalculateStatistics_management(raster, "1", "1", "")
    arcpy.BuildRasterAttributeTable_management(raster, "Overwrite")
    arcpy.env.rasterStatistics = 'STATISTICS 1 1 (0)'
    z= arcpy.env.rasterStatistics
    rastname = str(raster)
    outfile.write(rastname + " ")
    textstring = str(z)
    outfile.write(textstring + "\n")
outfile.close()

And it's not working 😞

This form doesn't work:

arcpy.env.rasterStatistics = 'STATISTICS 1 1 (0)'

How I can fix it?
Tags (2)
0 Kudos
2 Replies
JakeSkinner
Esri Esteemed Contributor
After running the Build Raster Attribute Table tool, the attribute table of the raster will contain a field called Value representing the pixel value, and a field called Count representing how many pixels of that Value.  You can then use the following code to write these value to an output text file:

lstRasters = arcpy.ListRasters("*")

logfile = open(r"c:\temp\pixels.txt", "w")

for raster in lstRasters:
    rows = arcpy.SearchCursor(raster)
    for row in rows:
        logfile.write("Value of " + str(row.value) + " = " + str(row.count) + " pixels" + "\n")

logfile.close()
0 Kudos
LukaszB_
New Contributor
It works perfect ! Great thanks! 🙂
0 Kudos