---
title: 2-D convolution (cross-correlation) with stride and padding
url: https://gurkanozkan.ai/learn/coding/mle-2-d-convolution-cross-correlation-with-stride-and-padding-21/
markdown: https://gurkanozkan.ai/learn/coding/mle-2-d-convolution-cross-correlation-with-stride-and-padding-21.md
kind: coding
difficulty: Easy
topics:
  - CNN
  - NumPy
json: https://gurkanozkan.ai/api/learn/coding/mle-2-d-convolution-cross-correlation-with-stride-and-padding-21.json
robots: noindex
---

# 2-D convolution (cross-correlation) with stride and padding

Apply a 2-D kernel to a single-channel image as deep-learning frameworks do (no kernel flip). Zero-pad by `padding` on every side; output size is `floor((H + 2p − kh)/stride) + 1` per dimension.

## Signature

```python
def conv2d(image, kernel, stride: int = 1, padding: int = 0) -> np.ndarray: ...
```

## Examples

Each call and the value it should give.

```python
>>> close(conv2d([[1,2,3],[4,5,6],[7,8,9]], [[1,0],[0,-1]]), [[-4.0, -4.0], [-4.0, -4.0]])
True

>>> close(conv2d([[1,2,3],[4,5,6],[7,8,9]], [[1]], stride=2), [[1.0, 3.0], [7.0, 9.0]])
True
```

## Hints

1. Apply the kernel as cross-correlation — no flip.
2. Output size = floor((H + 2p - kh)/stride) + 1 per dimension; zero-pad by padding on every side.
3. Use offset indexing over the window rather than per-pixel loops.

## Reference solution

```python
import numpy as np

def conv2d(image, kernel, stride=1, padding=0):
    img = np.asarray(image, float); ker = np.asarray(kernel, float)
    if padding:
        img = np.pad(img, padding)
    H, W = img.shape; kh, kw = ker.shape
    oh = (H - kh) // stride + 1; ow = (W - kw) // stride + 1
    out = np.zeros((oh, ow))
    for i in range(oh):
        for j in range(ow):
            out[i, j] = (img[i * stride:i * stride + kh, j * stride:j * stride + kw] * ker).sum()
    return out
```

## What a strong solution covers

- Correct output shape formula.
- Correct window indexing with stride.
- Explains cross-correlation vs convolution.
- Discusses im2col/GEMM vectorisation, multi-channel extension, and receptive fields.

## Common mistakes

- flipping the kernel
- off-by-one output sizes with stride > 1.
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
