Python Forum
speed up the "for loops"
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
speed up the "for loops"
#1
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()
Reply
#2
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?
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020