Sliding Window Implementation in OpenCV

A sliding window is very important tool in image processing and computer vision algorithms. Here is my code for a generic sliding window implementation. It is a very fast draft so may contain bugs. Use it at your own risk. You must acknowledge my name (Md. Iftekhar Tanveer) and email address ( if you use it in your code.

It is a simple linked list based implementation of sliding window. You can modify the Node structure to add or remove additional data. Just do not change prevWindow and nextWindow variables because that is required by the temporal window class.

// The basic Data Structure for Temporal Window
struct Node{
// --- Data Part of the Node ---
std::vector<cv::KeyPoint> kp;
cv::Mat desc;
// --- End of data part ---
cv::Ptr<Node> prevWindow; // Necessary for Navigation
cv::Ptr<Node> nextWindow; // Necessary for Navigation

class TemporalWindow{
int frameCapacity;
int currInstances;
cv::Ptr<Node> firstWindow;
cv::Ptr<Node> lastWindow;
TemporalWindow(TemporalWindow &a);
TemporalWindow(int capacity){
this->frameCapacity = capacity;
this->currInstances = 0;
firstWindow = NULL;
lastWindow = NULL;
this->frameCapacity = 1;
this->currInstances = 0;
firstWindow = NULL;
lastWindow = NULL;
void pushNewInstance(cv::Ptr<Node> newNode){
// Creating a new Node
newNode->nextWindow = NULL;
newNode->prevWindow = NULL;

// Adding the new node properly to the window
if(currInstances == 0)
lastWindow = firstWindow = newNode;
// Adding the new Node after endNode
newNode->prevWindow = lastWindow;
lastWindow->nextWindow = newNode;
lastWindow = newNode;

// If full, delete the first window
firstWindow = firstWindow->nextWindow;
firstWindow->prevWindow->nextWindow = NULL;
firstWindow->prevWindow = NULL;

// Count the number of instances
currInstances = (currInstances<frameCapacity)?++currInstances:

bool isEmpty(){
return (currInstances == 0);

int getCurrInstances(){
return currInstances;

// Complexity O(indx)
Node& operator[](int indx){
if (indx<0 || indx >= currInstances||isEmpty()){
"Index out of range or empty data structure","operator[]",
__FILE__, __LINE__));

cv::Ptr<Node> it = lastWindow;
for(int i = 0; i<indx;i++){
it = it->prevWindow;
return *it;

It can be used as below:

TemporalWindow tw(3); // Creating a sliding window with capacity 3

... ... ...

cv::Ptr<Node> nd;
 tw.pushNewInstance(nd);   // Push the data

... ... ...

keyp = tw[0].kp  // Data pushed most recently

keyp = tw[tw.getCurrInstances()-1].kp // oldest data within the range of the window


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s