Advertisement
Guest User

Untitled

a guest
Jul 26th, 2016
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. import numpy as np
  2. from scipy import ndimage
  3. from matplotlib import pyplot as plt
  4.  
  5. # generate some lowpass-filtered noise as a test image
  6. gen = np.random.RandomState(0)
  7. img = gen.poisson(2, size=(512, 512))
  8. img = ndimage.gaussian_filter(img.astype(np.double), (30, 30))
  9. img -= img.min()
  10. img /= img.max()
  11.  
  12. # use a boolean condition to find where pixel values are > 0.75
  13. blobs = img > 0.75
  14.  
  15. # label connected regions that satisfy this condition
  16. labels, nlabels = ndimage.label(blobs)
  17.  
  18. # find their centres of mass. in this case I'm weighting by the pixel values in
  19. # `img`, but you could also pass the boolean values in `blobs` to compute the
  20. # unweighted centroids.
  21. r, c = np.vstack(ndimage.center_of_mass(img, labels, np.arange(nlabels) + 1)).T
  22.  
  23. # find their distances from the top-left corner
  24. d = np.sqrt(r*r + c*c)
  25.  
  26. # plot
  27. fig, ax = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(10, 5))
  28. ax[0].imshow(img)
  29. ax[1].hold(True)
  30. ax[1].imshow(np.ma.masked_array(labels, ~blobs), cmap=plt.cm.rainbow)
  31. for ri, ci, di in zip(r, c, d):
  32. ax[1].annotate('', xy=(0, 0), xytext=(ci, ri),
  33. arrowprops={'arrowstyle':'<-', 'shrinkA':0})
  34. ax[1].annotate('d=%.1f' % di, xy=(ci, ri), xytext=(0, -5),
  35. textcoords='offset points', ha='center', va='top',
  36. fontsize='x-large')
  37. for aa in ax.flat:
  38. aa.set_axis_off()
  39. fig.tight_layout()
  40. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement