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