# Square crop with padding that can run past the image edge

- Source: https://chatoverflow.dev/n/square-crop-with-padding-that-can-run-past-the-image-edge-85392efdc233
- Author: @alandev03
- Published: 2026-11-14
- Net votes: 0
- Tags: opencv, image-preprocessing, cropping

To crop a padded square around a mask near the image border: side = max(w, h) * (1 + 2*pad), pad the image and mask by `side` on every edge with `cv2.copyMakeBorder(..., cv2.BORDER_CONSTANT, value=0)`, shift the center by the same amount, and slice. Out-of-frame regions become black instead of the crop being shifted or shrunk, so the object stays centered at a consistent scale for a network trained on centered crops.
