Sub topic 8
Cropping with NumPy slicing
This chapter assumes you can write basic Python functions and index NumPy arrays. It also assumes you know that OpenCV stores an image as a NumPy array of shape (height, width, channels) with channels in BGR order. The chapter covers how to cut a region out of an image, why that region can silently change the original, and which mistakes cause most cropping bugs.
Cropping is array slicing
OpenCV has no crop function. An image is a NumPy array, so you crop it by slicing. A crop is also called a region of interest, or ROI.
The slice has this form:
roi = img[y1:y2, x1:x2]The first index is the row range, which is the vertical axis y. The second index is the column range, which is the horizontal axis x. This is the opposite order from the (x, y) points you pass to drawing functions. The same image therefore needs [y, x] when you index it and (x, y) when you draw on it.
Slice bounds follow normal Python rules. The start is included and the stop is excluded. The slice img[50:200, 100:300] has 150 rows and 200 columns, so its shape is (150, 200, 3).
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
roi = img[50:200, 100:300]
print(roi.shape) # (150, 200, 3)The slice leaves the channel axis alone, so the crop keeps all three BGR channels. Writing img[50:200, 100:300, 0] would select only the blue channel and return a 2-D array.
A crop is a view, not a copy
A basic NumPy slice returns a view. A view is a new array object that shares its pixel memory with the original. No pixels are copied, so slicing is fast and uses almost no extra memory. The cost is that a change made through one array shows up in the other.
import cv2
img = cv2.imread("photo.jpg")
roi = img[50:200, 100:300]
roi[:] = (0, 0, 255) # paint the crop red
# The original image now has a red rectangle at the same place
cv2.imwrite("original_changed.png", img)Here roi[:] = (0, 0, 255) writes into the shared memory, so the region of img turns red. Drawing functions behave the same way. If you call cv2.rectangle(roi, ...), you also draw on the original image.
To get a crop that is independent of the original, call .copy():
import cv2
img = cv2.imread("photo.jpg")
roi_copy = img[50:200, 100:300].copy()
roi_copy[:] = (0, 0, 255) # the original is unchanged
cv2.imwrite("crop.png", roi_copy)You can check whether two arrays share memory with np.shares_memory(roi, img), which returns True for a view. The base attribute is another clue. A view has roi.base set to the array that owns the data, and an independent copy has base set to None.
The two cases call for different choices:
| Situation | Use a view | Use `.copy()` |
|---|---|---|
| Read-only analysis of the region | Yes | Not needed |
| Edit the region and keep the edit in the original | Yes | No |
| Edit the region and keep the original intact | No | Yes |
| Keep the crop after the large image is no longer needed | No | Yes |
The last row matters for memory. A view keeps the whole parent array alive. If you load a 40-megapixel photo, keep a small view of it in a list, and delete the photo variable, the full 120 MB buffer stays in memory. Copying the small crop lets Python free the large image.
Copying a patch back into the image
Because slices work on both sides of an assignment, you can paste one region into another. The region shapes must match exactly.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
patch = img[50:150, 100:200].copy() # 100 x 100 pixels
img[200:300, 300:400] = patch # also 100 x 100 pixels
cv2.imwrite("pasted.png", img)If the shapes differ, NumPy raises a ValueError about broadcasting. Resize the patch first with cv2.resize, as covered in the earlier resizing chapters.
Edge cases and common errors
Most cropping bugs come from a few sources. The first one is swapped axes.
Mixing up x and y
Suppose you have a bounding box as (x, y, w, h), which is the format many OpenCV functions return. The correct slice is:
x, y, w, h = 100, 50, 200, 150
roi = img[y:y + h, x:x + w]Writing img[x:x + w, y:y + h] runs without an error and returns the wrong region. If the image is smaller than the swapped indices, the result may be empty.
Out-of-range bounds fail silently
NumPy slices clamp their bounds to the array size instead of raising an error. If the image is 480 rows tall, img[400:900, 0:100] returns only 80 rows. A box that extends past the image edge therefore gives a smaller crop than you asked for, with no warning.
An empty region is also silent. img[500:600, 0:100] on a 480-row image returns an array of shape (0, 100, 3). The error appears later, often when cv2.imshow or cv2.resize fails on an empty array. Check the shape of the crop when the box comes from user input or a detector.
Negative indices
Negative numbers count from the end of the axis, as in any Python sequence. A negative coordinate that comes from a calculation, for example a box that starts slightly outside the image, does not mean "off the edge". It wraps around to the other side. img[-10:100, 0:100] is an empty slice, not a crop that starts at the top edge.
Safe cropping with clamping
A small helper handles both problems. It clamps the box to the image and returns an independent copy.
import cv2
def safe_crop(image, x, y, w, h):
"""Return a copy of the box (x, y, w, h), clipped to the image bounds."""
img_h, img_w = image.shape[:2]
x1 = max(0, x)
y1 = max(0, y)
x2 = min(img_w, x + w)
y2 = min(img_h, y + h)
if x1 >= x2 or y1 >= y2:
raise ValueError("Crop box does not overlap the image")
return image[y1:y2, x1:x2].copy()
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
crop = safe_crop(img, -20, 30, 300, 200)
print(crop.shape)The call above starts 20 pixels left of the image. The helper clips the left edge to 0, so the crop is narrower than 300 pixels.
Cropping with fractions and with a center
Sometimes you know the target in relative terms, such as "the middle half of the image" or "a square around a point". Compute integer bounds from the image size. Slice indices must be integers, so use int or round when you work with fractions.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
h, w = img.shape[:2]
# Middle half of the image in both directions
center_crop = img[h // 4: 3 * h // 4, w // 4: 3 * w // 4].copy()
# A square of side 2 * r centered on (cx, cy)
cx, cy, r = 300, 200, 80
square = img[cy - r: cy + r, cx - r: cx + r].copy()The second crop assumes the square fits inside the image. If the center is near an edge, pass the same bounds through safe_crop, or accept a smaller result.
A square crop is a common step before feeding images to a model that expects a fixed shape. The pattern is to crop first and then resize, so the content is not stretched.
Cropping a grid of tiles
Slicing in a loop splits an image into tiles. The loop below uses non-overlapping tiles and keeps the partial tiles at the right and bottom edges, because slice clamping handles them.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
h, w = img.shape[:2]
tile = 128
count = 0
for y in range(0, h, tile):
for x in range(0, w, tile):
piece = img[y:y + tile, x:x + tile]
cv2.imwrite(f"tile_{count:03d}.png", piece)
count += 1
print(count, "tiles written")Here cv2.imwrite does not need .copy() because it only reads the data. Edge tiles are smaller than 128 pixels on one side, which is the clamping behavior described earlier. If your downstream code needs equal sizes, skip the partial tiles or pad them.
The crop in the whole workflow
The diagram shows the order of steps in a safe crop.
Where cropping meets the next topics
Cropping connects directly to drawing. Because a view shares memory, drawing on a crop changes the original. The later chapter on drawing on a copy builds on this: call img.copy() once before you draw, and the original stays intact. The same rule applies here at the smaller scale of a single region.
Summary of the rules
- Slice as
img[y1:y2, x1:x2]: rows first, columns second. - The start index is included and the stop index is excluded.
- A slice is a view, so edits write through to the original.
- Use
.copy()for an independent crop. - NumPy clamps out-of-range bounds and wraps negative ones, so validate boxes from outside sources.
Exercise
A detector returns the box (x, y, w, h) = (400, 300, 200, 150) for a 640 x 480 image (width 640, height 480). You run roi = img[y:y + h, x:x + w] and then roi[:] = 0. What is the shape of roi, and what happens to the original image?
Show answer
The row range is 300:450, which fits inside 480 rows, so it gives 150 rows. The column range is 400:600, which fits inside 640 columns, so it gives 200 columns. The shape is (150, 200, 3). Since roi is a view, roi[:] = 0 sets those pixels to black in img too. To avoid changing the original, use img[y:y + h, x:x + w].copy().
Exercise
The same image is 640 wide and 480 tall. What shape does img[400:900, 600:800] return, and why does no error occur?
Show answer
The shape is (80, 40, 3). NumPy clamps slice bounds to the array size, so the rows run from 400 to 480 (80 rows) and the columns from 600 to 640 (40 columns). Slices do not raise errors for out-of-range bounds, which is why a helper like safe_crop should check boxes that come from outside sources.