1

In dealing with images represented as a matrix, I frequently find myself generate indices of a rectangular patch like:

si, sj = 0, 0  # upper-left corner
w, h = 2, 2  # patch width & height

indices = ((i, j) for i in range(si, si + h) for j in range(sj, sj + w))
print(list(indices))

# process corresponding pixels

Note that

  1. The generator code is lengthy to fit nicely into a single line, and I failed to find an elegant way to organize it into multiple ones.
  2. A nested for-loop is no good, as I need an iterable to feed into the next processing step.

I have a feeling that there exists a super elegant way to do this in Python. Is there? Or any elegant way to organize the generator code into multiple lines without using line continuation \?

Lingxi
  • 14,579
  • 2
  • 37
  • 93

2 Answers2

2

This sounds like a use-case for a generator function (see this StackOverflow question for a good explanation.). You would define it like:

def generator(si, sj, w, h): 
  for i in range(si, si + h):
    for j in range(sj, sj + w):
      yield (i, j)

You can then pass the function to your next processing step and iterate over it.

lmartens
  • 1,432
  • 2
  • 12
  • 19
2

Find the solution I want myself from this thread.

from itertools import product

si, sj = 0, 0  # upper-left corner
w, h = 2, 2  # patch width & height
indices = product(range(si, si + h), range(sj, sj + w))
print(list(indices))
Lingxi
  • 14,579
  • 2
  • 37
  • 93