Guest User

roi in Fiji/ImageJ

a guest
May 15th, 2013
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.32 KB | None | 0 0
  1. from ij import IJ
  2. from ij.io import DirectoryChooser, OpenDialog
  3. from ij.gui import GenericDialog
  4. import csv
  5. import os
  6.  
  7.  
  8. def run(image_filename, roi_filename=None, orientation_filename=None):
  9.     imp = IJ.openImage(image_filename)
  10.     roi = load_roi(roi_filename)
  11.     imp.setRoi(roi)
  12.     measure_area(imp)
  13.     imp.show()
  14.  
  15. def load_roi(roi_filename):
  16.     f = open(roi_filename, 'r')
  17.     x = []
  18.     y = []
  19.     reader = csv.DictReader(f, delimiter='\t')
  20.     for row in reader:
  21.         x.append(float(row['X']))
  22.         y.append(float(row['Y']))
  23.     f.close()
  24.     polygon = FloatPolygon(x,y)
  25.     roi = PolygonRoi(polygon, PolygonRoi.POLYGON)
  26.     return roi
  27.  
  28. def measure_area(imp):
  29.     pix = imp.getProcessor().getPixels()
  30.     total_pixels = len(pix)
  31.     roi = imp.getProcessor().getRoi()
  32.     w = imp.getWidth()
  33.     total = 0
  34.     above_thresh = 0
  35.     total_intensity = 0.
  36.     for i, p in enumerate(pix):
  37.         x = i % w
  38.         y = i / w # integer division
  39.         if roi.contains(x,y):
  40.             total += 1
  41.             if p > 100:
  42.                 above_thresh += 1
  43.             total_intensity += float(p)
  44.         IJ.showProgress(i, total_pixels)
  45.     if total == 0:
  46.         print 'total pixels inside roi = 0'
  47.         total = 1
  48.     IJ.showProgress(1)
  49.     stats = imp.getStatistics(Measurements.STD_DEV |
  50.         Measurements.CENTROID |
  51.         Measurements.CENTER_OF_MASS |
  52.         Measurements.MEAN)
  53.     print """Pixel count via stats: %d
  54. Pixel count via iterating over pixels: %d""" % (stats.pixelCount, total)
  55.  
  56. def get_options():
  57.     # Get image
  58.     i_od = OpenDialog("Choose image file", None)
  59.     image_filename = os.path.join(i_od.getDirectory(), i_od.getFileName())
  60.     # Get Region of Interest (roi)
  61.     r_od = OpenDialog("Choose roi file", None)
  62.     roi_filename = os.path.join(r_od.getDirectory(), r_od.getFileName())
  63.     # Get threshold value
  64.     gd = GenericDialog("Options")
  65.     gd.addNumericField("Threshold - just ignore, still hardcoded", 500, 0) # 500 default and zero d.p.
  66.     gd.showDialog()
  67.     if (image_filename is None) or \
  68.             (roi_filename is None) or \
  69.             gd.wasCanceled():
  70.         raise Exception("User canceled the dialog")
  71.     else:
  72.         threshold = gd.getNextNumber()
  73.         return (image_filename, roi_filename)
  74.  
  75. options = get_options()
  76. run(*options)
Advertisement
Add Comment
Please, Sign In to add comment