Python Forum

Full Version: speed up the "for loops"
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
my question here

Hello every one, I started learning Python in last 2 months. I find this one really tough for me. My goal is to process a image and return the inscribed circle's radius of a central pattern. The program is sooooooooo slow!


from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
img=np.array(Image.open('C:/Python/1-3.tif').convert('L'))

rows,cols=img.shape
print(rows)


for i in range(rows):
   for j in range(cols):
       if (img[i,j]<=128):
           img[i,j]=0
       else:
           img[i,j]=1

result = []
for o in range(0, (min (rows, cols)) / 2):
   k = (rows / 2 + o)
   l = (cols / 2 + o)
   m = (rows / 2 - o)
   n = (cols / 2 - o)
   for i in range(m, k):
       for j in range(n, l):
           if (img[i,j] == 1):
               counter = 0
               radius = min (rows - i, i, cols -j, j)
               for r in range(0, radius):
                   for alpha in range(0, 360):
                       xx = (i + r * np.cos(alpha))
                       yy = (j + r * np.sin(alpha))
                       x = int(xx)
                       y = int(yy)
                       if (img[x,y] == 0):
                           counter += 1
               if (counter == 3):
                   break
                   result.extend([r])
print max(result)


plt.figure("1")
plt.imshow(img,cmap='gray')
plt.axis('off')
plt.show()
You have there five nested for loops (probably each iterating over hundreths of values), so its no wonder that its slow. You should try to use numpy's features, for example your "binning" for loops can be replaced with simpler and much faster
img = np.where(img < 128, 0, 1)
Perhaps something similar can be done for some of your other for loops.

Do you realize that np.cos and np.sin take argument in radians?