---
title: Image Gradients
description: >-
  Compute Gradient Computation of Image of a given image using finite
  difference.
canonical: 'https://lightning.ai/docs/torchmetrics/stable/image/image_gradients'
---
# Image Gradients {#image-gradients}

## Functional Interface {#functional-interface}

### `torchmetrics.functional.image.image_gradients(img)` {#torchmetrics.functional.image.image_gradients}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/functional/image/gradients.py#L45-L80)

Compute [Gradient Computation of Image](https://en.wikipedia.org/wiki/Image_gradient) of a given image using finite difference.

Parameters:

**img** ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")) – An `(N, C, H, W)` input tensor where `C` is the number of image channels

Return type:

[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple "(in Python v3.15)")\[[`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)"), [`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")\]

Returns:

Tuple of `(dy, dx)` with each gradient of shape `[N, C, H, W]`

Raises:

*   [**TypeError**](https://docs.python.org/3/builtins/exceptions.html#TypeError "(in Python v3.15)") – If `img` is not of the type [`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)").
    
*   [**RuntimeError**](https://docs.python.org/3/builtins/exceptions.html#RuntimeError "(in Python v3.15)") – If `img` is not a 4D tensor.
    

Example

```python
>>> from torchmetrics.functional.image import image_gradients
>>> image = torch.arange(0, 1*1*5*5, dtype=torch.float32)
>>> image = torch.reshape(image, (1, 1, 5, 5))
>>> dy, dx = image_gradients(image)
>>> dy[0, 0, :, :]
tensor([[5., 5., 5., 5., 5.],
        [5., 5., 5., 5., 5.],
        [5., 5., 5., 5., 5.],
        [5., 5., 5., 5., 5.],
        [0., 0., 0., 0., 0.]])
```

Note

The implementation follows the 1-step finite difference method as followed by the TF implementation. The values are organized such that the gradient of \[I(x+1, y)-\[I(x, y)\]\] are at the (x, y) location

---

**Navigation**

- Parent: [Image](/docs/torchmetrics/1.9.0/image.md)
