Loop optimization for image processing
First of, I'm gonna give you a basic idea...

Instead of doing 2 loops over two different arrays, check their sizes first. Create a loop for the smaller of both array sizes. In that loop you will process that Array, and then create another loop for the remainder of unprocessed data.

This can be done for your two double fors you have in there. This way you could reduce the complexity from O(n+m) to O(n+(m-n))

The pseudo code is this...

if(Arr1 &gt; Arr2)
{ 
   process(Arr1, Arr2);
}
else if (Arr2 &gt; Arr1)
{
   process(Arr2, Arr1);
}
else //They're the same size!
{
  for(idx = 0; idx != count(any will do); ++idx)
  {
     //process Arr1
     //process Arr2
   }
}