Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I want to change the value of an individual pixel in a raster using arcpy. The code I wrote for changing the value is below, but it changes all of pixels in my raster. How can I set an individual pixel in my code?

import arcpy
import numpy
raster = arcpy.Raster(r"C:\test.jpg")
array = arcpy.RasterToNumPyArray(raster)
(height, width)=array.shape
for row in range(0,1):
    for col in range(0,1):

        newarray = array * 2.0

        newraster  = arcpy.NumPyArrayToRaster(newarray)
        newraster.save(r"C:\export.gdb\t")

Thanks

share|improve this question

1 Answer 1

up vote 10 down vote accepted

newarray = array * 2.0 performs the math on the entire array, not just on one element.

It should instead be something like this:

raster = arcpy.Raster(r"C:\test.jpg")
array = arcpy.RasterToNumPyArray(raster)

# modify cell
array[0,0] *= 2.0

# save to a new raster
newraster = NumPyArrayToRaster(array)
newraster.save(r"C:\export.gdb\t")

Or, if you want to use the loop variables instead of hard-code the row/column:

for row in range(0,1):
    for col in range(0,1):
        array[row,col] *= 2.0

Controlling the iteration directly with numpy is probably more efficient for a large amount of array modification, so consider looking at that documentation if you'd like to go that route. I don't have direct experience with it yet so can't include it in this Answer.

share|improve this answer
1  
Copying the array is unnecessary (numpy arrays are mutable!) and adds extra processing time and memory usage to the script, especially since nothing is being deleted. You'd be better served using numpy for this kind of task if you want to iterate over the cells. –  Paul Jul 8 at 12:39
    
Good point @Paul, the array is already a copy of the raster. I've updated the snippet. –  Erica Jul 8 at 13:03
3  
Actually, you can use array[0,0] *= 2 –  Paul Jul 8 at 13:07
    
@Erica thanks . i have another question : what do i do if i want to change a set of pixels? for example change pixels of two rows or two columns. –  wetland Jul 8 at 14:54
1  
In that case, you can use loops and go through additional rows, e.g. for row in range(0,2): –  Erica Jul 8 at 22:24

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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