Search results
Top results related to sliding window algorithm
Top Answer
Answered Jul 27, 2009 · 4 votes
Naive implementation:
private static IEnumerable<T[,]> GetWindows<T>( T[,] array, int windowWidth, int windowHeight){ for (var y = 0; y < array.GetLength(1) - windowHeight + 1; y++) { for (var x = 0; x < array.GetLength(0) - windowWidth + 1; x++) { var slice = new T[windowWidth, windowHeight]; CopyArray(array, x, y, slice, 0, 0, windowWidth, windowHeight); yield return slice; } }}
Helper method to copy between two-dimensional arrays:
private static void CopyArray<T>( T[,] src, int srcX, int srcY, T[,] dst, int dstX, int dstY, int width, int height){ for (var x = 0; x < width; x++) { for (var y = 0; y < height; y++) { dst[dstX + x, dstY + y] = src[srcX + x, srcY + y]; } }}
Test main:
private static void Main(string[] args){ var array = new string[5, 5]; for (var y = 0; y < array.GetLength(1); y++) { for (var x = 0; x < array.GetLength(0); x++) { array[x, y] = string.Format("({0}|{1})", x, y); } } foreach (var window in GetWindows(array, 3, 3)) { ShowArray(window); } Console.ReadLine();}private static void ShowArray<T>(T[,] array){ for (var x = 0; x < array.GetLength(0); x++) { for (var y = 0; y < array.GetLength(1); y++) { Console.Write(" {0}", array[x, y]); } Console.WriteLine(); } Console.WriteLine();}
Output:
(0|0) (0|1) (0|2)(1|0) (1|1) (1|2)(2|0) (2|1) (2|2)-(1|0) (1|1) (1|2)(2|0) (2|1) (2|2)(3|0) (3|1) (3|2)(2|0) (2|1) (2|2)(3|0) (3|1) (3|2)(4|0) (4|1) (4|2)(0|1) (0|2) (0|3)(1|1) (1|2) (1|3)(2|1) (2|2) (2|3)(1|1) (1|2) (1|3)(2|1) (2|2) (2|3)(3|1) (3|2) (3|3)(2|1) (2|2) (2|3)(3|1) (3|2) (3|3)(4|1) (4|2) (4|3)(0|2) (0|3) (0|4)(1|2) (1|3) (1|4)(2|2) (2|3) (2|4)(1|2) (1|3) (1|4)(2|2) (2|3) (2|4)(3|2) (3|3) (3|4)(2|2) (2|3) (2|4)(3|2) (3|3) (3|4)(4|2) (4|3) (4|4)
Now all you have to do is apply the same technique as shown in that blog post :)
1/5
Top Answer
Answered Mar 24, 2021 · 3 votes
As David indicates, you can't use the sliding/stretching window technique when there are negative numbers in the array, because the sum doesn't grow monotonically with the window size.
You can still solve this in O(n log n) time, though, using a technique that is usually used for the "sliding window minimum/maximum" problem.
First, transform your array into a prefix sum array, by replacing each element with the sum of that element and all the previous ones. Now your problem changes to "find the closest pair of elements with difference >= X" (assuming array[-1]==0).
As you iterate though the array, you need to find, for each i, the latest index j such that j < i and array[j] <= array[i]-x.
In order to do that quickly, first note that array[j] will always be less than all the following elements up to i, because otherwise there would be a closer element to choose.
So, as you iterate through the array, maintain a stack of the indexes of all elements that are smaller than all the later elements you've seen. This is easy and takes O(n) time overall -- after processing each i, you just pop all the indexes with >= values, and then push i.
Then for each i, you can do a binary search in this stack to find the latest index with a small enough value. The binary search works, because the values for index in the stack increase monotonically -- each element must be less than all the following ones.
With the binary search, to total time increases to O(n log n).
In JavaScript, it looks like this:
var shortestSubarray = function(A, K) { //transform to prefix sum array let sum=0; const sums = A.map(val => { sum+=val; return sum; }); const stack=[]; let bestlen = -1; for(let i=0; i<A.length; ++i) { const targetVal = sums[i]-K; //binary search to find the shortest acceptable span //we will find the position in the stack *after* the //target value let minpos=0; let maxpos=stack.length; while(minpos < maxpos) { const testpos = Math.floor(minpos + (maxpos-minpos)/2); if (sums[stack[testpos]]<=targetVal) { //value is acceptable. minpos=testpos+1; } else { //need a smaller value - go left maxpos=testpos; } } if (minpos > 0) { //found a span const spanlen = i - stack[minpos-1]; if (bestlen < 0 || spanlen < bestlen) { bestlen = spanlen; } } else if (bestlen < 0 && targetVal>=0) { // the whole prefix is a valid span bestlen = i+1; } // Add i to the stack while(stack.length && sums[stack[stack.length-1]] >= sums[i]) { stack.pop(); } stack.push(i); } return bestlen;};
Leetcode says:
SUCCESS:
Runtime: 216 ms, faster than 100.00% of JavaScript online submissions for Shortest Subarray with Sum at Least K.
Memory Usage: 50.1 MB, less than 37.37% of JavaScript online submissions for Shortest Subarray with Sum at Least K.
I guess most people used a slower algorithm.
2/5
Top Answer
Answered Dec 21, 2014 · 3 votes
It might be easier for you to understand what's going on if you try using flatten=False to create a 'grid' of windows onto the image:
import numpy as npfrom scipy.misc import lenafrom matplotlib import pyplot as plt-img = lena()print(img.shape)# (512, 512)# make a 64x64 pixel sliding window on img. win = sliding_window(img, (64, 64), shiftSize=None, flatten=False)print(win.shape)# (8, 8, 64, 64)# i.e. (img_height / win_height, img_width / win_width, win_height, win_width)plt.imshow(win[4, 4, ...])plt.draw()# grid position [4, 4] contains Lena's eye and nose
To get the corresponding pixel coordinates, you could do something like this:
def get_win_pixel_coords(grid_pos, win_shape, shift_size=None): if shift_size is None: shift_size = win_shape gr, gc = grid_pos sr, sc = shift_size wr, wc = win_shape top, bottom = gr * sr, (gr * sr) + wr left, right = gc * sc, (gc * sc) + wc return top, bottom, left, right# check for grid position [3, 4]t, b, l, r = get_win_pixel_coords((3, 4), (64, 64))print(np.all(img[t:b, l:r] == win[3, 4, :, :]))# True
With flatten=True, the 8x8 grid of 64x64-pixel windows will just get flattened out into 64-long vector of 64x64-pixel windows. In that case you could use something like np.unravel_index to convert from the 1D vector index into a tuple of grid indices, then use these to get the pixel coordinates as above:
win = sliding_window(img, (64, 64), flatten=True)-grid_pos = np.unravel_index(12, (8, 8))t, b, l, r = get_win_pixel_coords(grid_pos, (64, 64))print(np.all(img[t:b, l:r] == win[12]))# True
OK, I'll try and address some of the questions you raised in the comments.
I want the pixel location of the window relative to the actual pixel dimensions original image.
Perhaps I was not clear enough - you can already do this using something like my get_win_pixel_coords() function, which gives you the top, bottom, left and right coordinates of the window relative to the image. For example:
win = sliding_window(img, (64, 64), shiftSize=None, flatten=False)-fig, (ax1, ax2) = plt.subplots(1, 2)ax1.hold(True)ax1.imshow(win[4, 4])ax1.plot(8, 9, 'oy') # position of Lena's eye, relative to this windowt, b, l, r = get_win_pixel_coords((4, 4), (64, 64))ax2.hold(True)ax2.imshow(img)ax2.plot(t + 8, l + 9, 'oy') # position of Lena's eye, relative to whole imageplt.show()
Also notice that I've updated get_win_pixel_coords() to deal with cases where shiftSize is not None (i.e the windows don't perfectly tile the image with no overlap).
So I'm guessing that in that case, I should just make the grid be equal to the original image's dimensions, is that right? (instead of using 8x8).
No, if the windows tile the image without overlap (i.e. shiftSize=None, which I've assumed so far), then if you made the grid dimensions equal to the pixel dimensions of the image, every window would just contain a single pixel!
So in my case, for an image of width: 360 and height: 240, would that mean I use this line: grid_pos = np.unravel_index(*12*, (240, 360)). Also, what does 12 refer to in this line?
As I said, making the 'grid size' equal to the image dimensions would be pointless, since every window would contain only a single pixel (at least, assuming that the windows are non-overlapping). The 12 would refer to the index into the flattened grid of windows, e.g.:
x = np.arange(25).reshape(5, 5) # 5x5 grid containing numbers from 0 ... 24x_flat = x.ravel() # flatten it into a 25-long vectorprint(x_flat[12]) # the 12th element in the flattened vector# 12row, col = np.unravel_index(12, (5, 5)) # corresponding row/col index in xprint(x[row, col])# 12
I am shifting 10 pixels with each window, and the first sliding window starts from coordinates 0x0 on the image, and the second starts from 10x10, etc, then I want it the program to return not just the window contents but the coordinates corresponding to each window, i.e. 0,0, and then 10,10, etc
As I said, you can already get the position of the window relative to the image using the top, bottom, left, right coordinates returned by get_win_pixel_coords(). You could wrap this up into a single function if you really wanted:
def get_pixels_and_coords(win_grid, grid_pos): pix = win_grid[grid_pos] tblr = get_win_pixel_coords(grid_pos, pix.shape) return pix, tblr# e.g.:pix, tblr = get_pixels_and_coords(win, (3, 4))
If you want the coordinates of every pixel in the window, relative to the image, another trick you could use is to construct arrays containing the row and column indices of every pixel in the image, then apply your sliding window to these:
ridx, cidx = np.indices(img.shape)r_win = sliding_window(ridx, (64, 64), shiftSize=None, flatten=False)c_win = sliding_window(cidx, (64, 64), shiftSize=None, flatten=False)-pix = win[3, 4] # pixel valuesr = r_win[3, 4] # row index of every pixel in the windowc = c_win[3, 4] # column index of every pixel in the window
3/5
Top Answer
Answered Nov 25, 2011 · 237 votes
Generally speaking a sliding window is a sub-list that runs over an underlying collection. I.e., if you have an array like
[a b c d e f g h]-
a sliding window of size 3 would run over it like
[a b c] [b c d] [c d e] [d e f] [e f g] [f g h]
This is useful if you for instance want to compute a running average, or if you want to create a set of all adjacent pairs etc.
4/5
www.geeksforgeeks.org › window-sliding-techniqueSliding Window Technique - GeeksforGeeks
www.geeksforgeeks.org › window-sliding-techniqueJul 8, 2024 · Sliding Window Technique is a method used to efficiently solve problems that involve defining a window or range in the input data (arrays or strings) and then moving that window across the data to perform some operation within the window.
www.freecodecamp.org › news › sliding-window-techniqueHow to Use the Sliding Window Technique – Algorithm Example ...
www.freecodecamp.org › news › sliding-window-techniqueJan 11, 2024 · The sliding window technique is an algorithmic approach used in computer science and signal processing. It involves selecting a fixed-size subset, or "window," from a larger dataset and moving this window through the dataset in a step-wise fashion.
stackoverflow.com › questions › 8269916What is Sliding Window Algorithm? Examples? - Stack Overflow
stackoverflow.com › questions › 8269916Oct 20, 2013 · The Sliding window is a problem-solving technique for problems that involve arrays/lists. These problems are easy to solve using a brute force approach in O(n^2) or O(n^3). Using the 'sliding window' technique, we can reduce the time complexity to O(n).
builtin.com › data-science › sliding-window-algorithmSliding Window Algorithm Explained | Built In
builtin.com › data-science › sliding-window-algorithmDec 12, 2023 · Sliding Window Algorithm Explained. The sliding window is a data structure technique that transforms two nested loops into a single loop within an array or list. Learn more with examples.
leetcodethehardway.com › sliding-windowSliding Window | LeetCode The Hard Way
leetcodethehardway.com › sliding-windowSliding Window is a technique used for iterating through a finite data set, typically an array, in a specific and controlled way. It involves creating a window, which is a subset of the data, that "slides" through the larger data set, typically one element at a time, while performing a specific operation on each subset of the data.
favtutor.com › blogs › sliding-window-algorithmSliding Window Algorithm (with Java, C++ and Python code)
favtutor.com › blogs › sliding-window-algorithmJun 14, 2023 · The Sliding Window algorithm is a method for finding a subset of elements that satisfy a certain condition in issues. Maintaining a window containing elements from an array or string while advancing the window in a particular direction until the required subset is found is how this method operates.
quanticdev.com › sliding-windowSliding Window Technique - QuanticDev
quanticdev.com › sliding-windowSliding Window Technique is a subset of Dynamic Programming, and it frequently appears in algorithm interviews. In this article, you will learn how Sliding Window Technique works (with animations), tips and tricks of using it, along with its applications on some sample questions.
Searches related to sliding window algorithm