Rolling or sliding window iterator?

后端 未结 23 1449
南方客
南方客 2020-11-21 05:23

I need a rolling window (aka sliding window) iterable over a sequence/iterator/generator. Default Python iteration can be considered a special case, where the window length

23条回答
  •  忘了有多久
    2020-11-21 06:06

    This is an old question but for those still interested there is a great implementation of a window slider using generators in this page (by Adrian Rosebrock).

    It is an implementation for OpenCV however you can easily use it for any other purpose. For the eager ones i'll paste the code here but to understand it better I recommend visiting the original page.

    def sliding_window(image, stepSize, windowSize):
        # slide a window across the image
        for y in xrange(0, image.shape[0], stepSize):
            for x in xrange(0, image.shape[1], stepSize):
                # yield the current window
                yield (x, y, image[y:y + windowSize[1], x:x + windowSize[0]])
    

    Tip: You can check the .shape of the window when iterating the generator to discard those that do not meet your requirements

    Cheers

提交回复
热议问题