smathot

Center of gravity

Jan 16th, 2013
575
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.59 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. from matplotlib import pyplot as plt
  4. from scipy import ndimage
  5. import sys
  6. import os
  7. import numpy as np
  8.  
  9. def centerOfGravity(src, show=False, invert=False, edgeDetect=True):
  10.  
  11.     """
  12.     Gets the center of gravity for an image
  13.  
  14.     Arguments:
  15.     src     --  a 3d numpy array or a string corresponding to an image file
  16.  
  17.     Keyword arguments:
  18.     show    --  indicates whether the results should be plotted (default=False)
  19.     invert  --  indicates whether the colors should be inverted, which makes
  20.                 sense if the background is white (default=True)
  21.  
  22.     Returns:
  23.     An (x, y) tuple of floats that gives the center of gravity for the image
  24.     """
  25.  
  26.     # Read if the image is a string and not a numpy array
  27.     if isinstance(src, basestring):
  28.         src = plt.imread(src)
  29.  
  30.     # Invert the 0-1 values
  31.     if invert:
  32.         src = 1-src
  33.  
  34.     # Edge detection using Sobel operator, see
  35.     # <http://scipy-lectures.github.com/advanced/image_processing/index.html#edge-detection>
  36.     if edgeDetect:
  37.         sx = ndimage.sobel(src, axis=0, mode='constant')
  38.         sy = ndimage.sobel(src, axis=1, mode='constant')
  39.         src = np.hypot(sx, sy)
  40.  
  41.     # Get center of mass
  42.     y, x, col = ndimage.measurements.center_of_mass(src)
  43.  
  44.     # Optionally plot
  45.     if show:
  46.         plt.imshow(src)
  47.         plt.axvline(x)
  48.         plt.axhline(y)
  49.         plt.annotate('%.1f,%.1f' % (x,y), (x,y))
  50.         plt.show()
  51.  
  52.     return x, y
  53.  
  54. if __name__ == '__main__':
  55.  
  56.     path = 'images'
  57.     for src in os.listdir(path):
  58.         x, y = centerOfGravity(os.path.join(path, src), show=True,
  59.             invert='--invert' in sys.argv,
  60.             edgeDetect='--edgeDetect' in sys.argv)
  61.         print 'The center of gravity is %.1f, %.1f' % (x,y)
Advertisement
Add Comment
Please, Sign In to add comment