0

I decided to try a project where I grab slices from a single image to generate data.While the program works, I was forced to use a for-loop to index these, so the it runs very slowly. I was wondering if there may be a better way to design the function. My current code for the grab function is:

def grab(segment_count, width, length, img):
  max_x_idx, max_y_idx, _ = img.shape
  max_x_idx -= length
  max_y_idx -= width

  x_1_list = np.random.randint(0,max_x_idx,segment_count)
  y_1_list = np.random.randint(0,max_y_idx,segment_count)

  x_2_list = x_1_list + length
  y_2_list = y_1_list + width

  out = np.array([image[x_1_list[i]:x_2_list[i], y_1_list[i]:y_2_list[i],] for i in range(segment_count)])
  return out

this was the closest information I found (plus several near-duplicates), but I couldn't find a way to apply any of the solutions to my problem, so I am still lost.

(sorry if it's not the most pythonic; I taught myself to code in python and haven't taken any official coding classes, so my conventions may be a little harder to follow)


Here's the code I used to test the function:

test = grab(10,256,256,image)
print(test.shape)
plt.imshow(test[0])
plt.show()
plt.subplots(2,5)
h = 0
for i in range(2):
  for t in range(5):
    plt.subplot(2,5,h+1)
    plt.imshow(test[h])
    plt.axis("off")
    h+=1
plt.show()

Here's the source image I'm currently using

And here was the output

  • Are you sure it's slow due to the loop: How large is `segment_count`? – Timus Oct 23 '20 at 15:12
  • Maybe you could add an input and output image so we can see what this uncommented, un-runnable code with no `import` statements is trying to do, please? – Mark Setchell Oct 23 '20 at 15:24
  • Crap, you're right. I doubt it's the loop, and I think I know what is actually causing the slowdown. I can't imagine that grabbing 32 (or 64) batches would cost too much in computation. – Ayden King Oct 23 '20 at 15:28
  • @MarkSetchell I tried to include some more info, but I haven't posted anything before here and I don't know if I included enough. Let me know if there is more that I should include – Ayden King Oct 23 '20 at 15:40

0 Answers0