Differences between revisions 5 and 6
Revision 5 as of 2009-03-23 19:50:25
Size: 1411
Comment:
Revision 6 as of 2012-06-18 04:49:44
Size: 572
Editor: SteveLudtke
Comment:
Deletions are marked like this. Additions are marked like this.
Line 4: Line 4:
{{{#!python
a = test_image()
for k in a.get_zsize():
    for j in a.get_ysize():
        for i in a.get_xsize():
            pixel_value = a.get(i,j,k) # get the pixel value
            a.set(i,j,k,pixel_value*3) # set the pixel value
}}}

Note that if you know the dimensionality of the image, say for example if the image is 2D, you can ignore the 3rd dimension when you use the '''get''' and '''set''' functions, for example like this:
Line 17: Line 7:
for j in a.get_ysize():
    for i in a.get_xsize():
        pixel_value = a.get(i,j) # get the pixel value using 2D syntax
        a.set(i,j,pixel_value*3) # set the pixel value using 2D syntax
for k in a["nz"]:
    
for j in a["ny"]:
     for i in a["nx"]:
     pixel_value = a[i,j,k] # get the pixel value
            a[i,j,k]=pixel_value*3 # set the pixel value
Line 23: Line 14:
Also, there is a generic 1D approach one can take using 1D syntax and the '''get_size''' function, which returns the total number of pixels. For example: Note that you can do any of:
Line 26: Line 17:
a = test_image() # This image is 2D
for i in a.get_size(): # Note get_size, not get_xsize etc.
    pixel_value = a.get(i) # get the pixel value using 1D syntax
    a.set(i,pixel_value*3) # set the pixel value using 1D syntax
a[x]
a[x,y]
a[x,y,z]
a[attr_name]
}}}
Line 31: Line 23:
a = EMData(10,1,1) # a 1D EMData object
for i in a.get_size(): # In the 1D case this is the same as get_xsize
    # use 1D get and set functions as above
}}}
The fourth form allows getting and setting attributes equivalent to set_attr() and get_attr().

Iterating through the pixels in the EMData object

In your Python script you can use commands like this to iterate through the pixels in an EMData object

   1 a = test_image()
   2 for k in a["nz"]:
   3     for j in a["ny"]:
   4         for i in a["nx"]:
   5             pixel_value = a[i,j,k] # get the pixel value
   6             a[i,j,k]=pixel_value*3 # set the pixel value

Note that you can do any of:

   1 a[x]
   2 a[x,y]
   3 a[x,y,z]
   4 a[attr_name]

The fourth form allows getting and setting attributes equivalent to set_attr() and get_attr().

EMAN2/Tutorials/iter_pixels (last edited 2015-08-14 22:11:14 by SteveLudtke)