0

I have a task where i need to specify the upper left coordinate of the smaller image in the larger image. I implemented this code, however it is too slow since I have a time limit of 20 seconds, and in some datasets I have 3000 images. How can this be implemented more effectively? I can use numpy, scipy and all packages from the standard python library.

import numpy as np
from PIL import Image

map_image_path = input()
map_image = Image.open(map_image_path)
map_ar = np.asarray(map_image)
map_ar_y, map_ar_x  = map_ar.shape[:2]

i = int(input())
dimensions = input()
patches=list()

for k in range(i):
  patch_image_path = input()
  patches.append(Image.open(patch_image_path))

for j in range(i):
  patch_ar = np.asarray(patches[j])
  patch_ar_y, patch_ar_x = patch_ar.shape[:2]
  stop_x = map_ar_x - patch_ar_x + 1
  stop_y = map_ar_y - patch_ar_y + 1

  for x in range(0, stop_x):
    for y in range(0, stop_y):
      x2 = x + patch_ar_x
      y2 = y + patch_ar_y
      picture = map_ar[y:y2, x:x2]
      if np.array_equal(picture, patch_ar):
        print(str(x) + "," + str(y))
HansHirse
  • 18,010
  • 10
  • 38
  • 67
Joe
  • 500
  • 1
  • 4
  • 11
  • 1
    Is this some kind of exercise? Why would you implement this yourself, this has been done many times before in other packages https://scikit-image.org/docs/dev/auto_examples/features_detection/plot_template.html. Here's a paper on the algorithm they use: https://www.researchgate.net/publication/226887830_Fast_Normalized_Cross-Correlation – Robin De Schepper Mar 15 '20 at 01:13
  • It works, but again it's too slow, for 4 images i have execution time about 2.7 seconds. – Joe Mar 15 '20 at 01:52
  • And I can't use skimage module. – Joe Mar 15 '20 at 01:58
  • 2
    Well that feels like an artificial restriction, homework questions are allowed on StackOverflow but most people, me included, except a greater deal of effort for homework questions. Can you show us what you've tried to improve your algorithm? I can tell you that the problem is that you've created a O(n^3)-ish algorithm for your problem: You construct a big array, for each pixel in an array, and then have to compare each pixel with another array. Imagine repeating comparing 250 pixels of the patch image to a slice of 250 pixels for each pixel in the 500 x 500 pixels of just 1 of your images. – Robin De Schepper Mar 15 '20 at 12:01
  • 3
    That's the brute force approach and the time limit was given to you exactly so you'd have to think of a more clever way to solve this problem. – Robin De Schepper Mar 15 '20 at 12:03
  • 1
    Have you thought of processing all four in parallel? – Mark Setchell Mar 16 '20 at 21:47

0 Answers0