Sobel Derivative and Custom Filter
Sobel derivative calculates the derivative in x and y directions. Thus, I decided to create customized 2D filter to calculate the derivative in the direction of 45 and -45 degree angles, respectively.
The customized kernel for 45 degree is:
$$
\begin{bmatrix}
0 & 1 & 2 \\
-1 & 0 & 1 \\
-2 & -1 & 0
\end{bmatrix}
$$
The kernel for -45 degrees is:
$$
\begin{bmatrix}
-2 & -1 & 0 \\
-1 & 0 & 1 \\
0 & 1 & 2
\end{bmatrix}
$$
At each point of the image, we calculate the gradient in that point, by combining both results above. Take absolute value of gradients at  45  and at  −45  degree angle, then weighted-average them to make the gradient
Convolution operator is 3 x 3 as we need to calculate the difference between the neighboring cells, and border type was set as default (reflective).
# import and convert the image into gray scale 
img = cv2.imread(F'/content/gdrive/.../myhouse.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# convolution operator to apply on the entire image matrix
kernel_pos = np.array([[0,1,2],[-1,0,1],[-2, -1, 0]])
kernel_neg = np.array([[-2, -1, 0],[-1, 0, 1],[0, 1, 2]])
# calculate the grad with respect to 45 and -45 degrees
grad_pos = cv2.filter2D(img,-1,kernel_pos)
grad_neg = cv2.filter2D(img,-1,kernel_neg)
# calculate into to make absolute values 
abs_grad_pos = cv2.convertScaleAbs(grad_pos)
abs_grad_neg = cv2.convertScaleAbs(grad_neg)
# calculate gradient of that point
grad = cv2.addWeighted(abs_grad_pos, 0.5, abs_grad_neg, 0.5, 0)
# show directional derivative
fig = plt.figure(figsize=(12,10))
ax = fig.add_subplot(121)
ax.imshow(img)
ax = fig.add_subplot(122)
ax.imshow(grad)
