title: What is the best way to calculate radial average of the image with python?
body: <p>I have a square image, for example this one:</p>
  
  <p><a href="https://i.stack.imgur.com/yeODB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yeODB.png" alt="Scipy coin demo image"></a></p>
  
  <p>and I would like to calculate the 1D average of the image for each radius from the position (0,0). I have written some code to do so, but first of all it very slow even for small images, secondly I see that there are also some problems with the idea behind it. Code is here:</p>
  
  <pre><code>import matplotlib.pyplot as plt
  import numpy as np
  import collections
  from skimage import data
  
  image = data.coins()
  image = image[:,0:303]
  print(image.shape)
  
  projection = {}
  total_count = {}
  
  for x_i,x in enumerate(image):
      for y_i,y in enumerate(x):
          if round(np.sqrt(x_i**2+y_i**2),1) not in projection:
              projection[round(np.sqrt(x_i**2+y_i**2),1)] = y
              total_count[round(np.sqrt(x_i**2+y_i**2),1)] = 1
          elif np.sqrt(round(np.sqrt(x_i**2+y_i**2),1)) in projection:
              projection[round(np.sqrt(x_i**2+y_i**2),1)] += y
              total_count[round(np.sqrt(x_i ** 2 + y_i ** 2), 1)] += 1
  
  od = collections.OrderedDict(sorted(projection.items()))
  x, y = [],[]
  
  for k, v in od.items():
      x.append(k)
      y.append(v/total_count[k])
  
  plt.plot(x,y)
  plt.xlabel('Radius from (0,0)')
  plt.ylabel('Averaged pixel value')
  plt.show()
  </code></pre>
  
  <p>The result of the code looks like this:</p>
  
  <p><a href="https://i.stack.imgur.com/VsPcX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VsPcX.png" alt="Result of radius average of picture"></a></p>
  
  <p>Has anyone have some clue how to improve my the script? I also don't know why in some cases there are some spikes which have very small average value. I would really appreciate some hints. Thanks!</p>