it's super inefficient - to call getMatRef() within a loop. Please, call it once outside of the loop. Also, please, use nested loop and .at<Vec3b>() operator instead of 1D access. The assert for array continuity should be removed.