# Calculate the gradient of images

I would like to calculate the gradient map of an image, which is the difference between adjacent pixels. I need to use the gradient maps as loss functions for back propagation to update network parameters, like TV Loss used in style transfer. Now I am confused about two implementation methods on the Internet.
The first is:

import torch
import torch.nn.functional as F

`````` if h_x is None and w_x is None:
h_x = x.size()[2]
w_x = x.size()[3]

r  = F.pad(x, (0, 1, 0, 0))[:, :, :, 1:]
l = F.pad(x, (1, 0, 0, 0))[:, :, :, :w_x]
t = F.pad(x, (0, 0, 1, 0))[:, :, :h_x, :]
b = F.pad(x, (0, 0, 0, 1))[:, :, 1:, :]
xgrad = torch.pow(torch.pow((r - l) * 0.5, 2) + torch.pow((t - b) * 0.5, 2), 0.5)
``````

While the second is :

``````import torch
import torch.nn as nn
import torch.nn.functional as F
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

def __init__(self):

kernel_x = [[-1., 0., 1.], [-2., 0., 2.], [-1., 0., 1.]]
kernel_x = torch.FloatTensor(kernel_x).unsqueeze(0).unsqueeze(0).to(device)
kernel_y = [[-1., 0., 1.], [-2., 0., 2.], [-1., 0., 1.]]
kernel_y = torch.FloatTensor(kernel_y).unsqueeze(0).unsqueeze(0).to(device)

def forward(self, x):
To compute the gradient of image (i.e. applying sobel filter), in the second code snippet, the line:`kernel_y = [[-1., 0., 1.], [-2., 0., 2.], [-1., 0., 1.]]` calculates partial derivative of x again, instead it should be corrected as `kernel_y = [[-1., -2., -1.], [0., 0., 0.], [1., 2., 1.]]` to compute y derivate.