Optimizing gradient function in C++
Include what you use

We use std::abs and std::vector but the code lacks the necessary includes:

#include &lt;cmath&gt;
#include &lt;vector&gt;


Perform a single task well

Why do we perform the Gaussian blur?  What if the input is already sufficiently blurred, or if it needs a bigger kernel?

If we make the caller responsible for this preparation step, we give it more control, and we can focus on a single responsibility in this function.

Fix the memory leak

This allocation is never released:

dirImg = new unsigned char[grey.cols*grey.rows];


In fact, this entire (global) array seems only to be assigned to, and never used, so we could remove it entirely.

Simplified indexing

It might be easier to use index throughout, and add rows or columns directly with ±grey.cols and ±1:

      const int index = i*grey.cols + j;
      int com1 = smoothImg[index + grey.cols + 1] - smoothImg[index - grey.cols - 1];
      int com2 = smoothImg[index - grey.cols + 1] - smoothImg[index + grey.cols - 1];
      int gx = std::abs(com1 + com2
                        + smoothImg[index + 1] - smoothImg[index + 1]);
      int gy = std::abs(com1 - com2
                        + smoothImg[index + grey.cols] - smoothImg[index - grey.cols]);


Use the standard library

There's no need to (badly) re-write std::hypot() for the computation of sum (also, drop the if (0) - that's always false).

      const int sum = std::hypot(gx, gy);


Saturate, don't overflow

The std::hypot() value could conceivably be larger than the range of int, or of gradImg[] (depending on the relative sizes of the target's integer types) - in such cases, we should std::clamp the value to the possible range, rather than suffering Undefined Behaviour.

Spelling

Prefer standard spelling: gradient, not gradiant.