Generate indices of a rectangular patch

2019-07-29 19:44发布

问题:

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 \?

回答1:

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.



回答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))