Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 54 ยท Geometric Transformations

Resizing, Cropping and Flipping

Resize images with cv2.resize and its interpolation flags, keep the aspect ratio, crop by slicing, flip and rotate by 90 degrees, and rebuild nearest and bilinear resizing in NumPy.

Almost every vision pipeline starts by changing the shape of an image. A neural network wants 224 by 224 input. A thumbnail needs to be small. A face detector runs faster on a shrunken frame. A selfie camera is mirrored. These are the simplest geometric transformations: they move pixels around without changing what the picture shows.

This lesson covers cv2.resize, cropping, flipping and 90-degree rotation. You will also meet the most common resize bug (width and height swapped) and write nearest-neighbor and bilinear resizing yourself in NumPy, so you know what the interpolation flags actually do. The real cv2 calls are shown read-only; the NumPy stand-ins run live. For the array basics, see Images Are NumPy Arrays.

Resizing with cv2.resize

Python
import cv2

img = cv2.imread("photo.jpg")            # shape (480, 640, 3): 480 rows, 640 columns
print(img.shape)

small = cv2.resize(img, (320, 240))                       # dsize = (width, height)
half  = cv2.resize(img, None, fx=0.5, fy=0.5)             # scale factors instead
big   = cv2.resize(img, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)

The signature is cv2.resize(src, dsize, fx=0, fy=0, interpolation=cv2.INTER_LINEAR). You give either an output size dsize or the scale factors fx and fy (with dsize=None), not both.

Warning: dsize is (width, height), but img.shape is (height, width, channels). Passing img.shape[:2] straight into resize gives a transposed result. Write cv2.resize(img, (new_w, new_h)) and name the variables.

Pick an interpolation flag

INTER_NEAREST Fastest. Blocky. Good for masks and labels.
INTER_LINEAR The default. Smooth enough, fast.
INTER_CUBIC Sharper when enlarging. Slower.
INTER_AREA Best choice when shrinking.

Details and pictures are in the Interpolation lesson.

1 / 2

When you enlarge or shrink, the new image has a different pixel grid from the old one, so every output pixel must be estimated from the input. The interpolation flag chooses how. The default INTER_LINEAR is a good all-round choice. Use INTER_AREA when shrinking (it averages the pixels that collapse into one, which avoids jagged aliasing) and INTER_NEAREST for label maps or masks where blending two class ids would create a meaningless third one. A fuller comparison is in Interpolation and Image Quality.

Keeping the aspect ratio

If you pick both a new width and a new height freely, the image gets stretched. To keep the shapes right, choose one dimension and compute the other from the original ratio.

Python
def resize_to_width(img, new_w):
    h, w = img.shape[:2]
    new_h = round(h * new_w / w)
    return cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_AREA)

Models with a fixed square input often use letterboxing: scale so the longer side fits, then pad the rest with a constant color. That keeps the content undistorted at the cost of some empty border.

Python Aspect-ratio arithmetic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Cropping is slicing

OpenCV has no crop function, because an image is a NumPy array and slicing already does the job. The pattern is img[y1:y2, x1:x2]: rows first, then columns, with the end index excluded.

Python
face = img[50:200, 120:260]       # rows 50..199, columns 120..259

A slice is a view, not a copy: it shares memory with the original, so drawing on the crop changes the full image. Add .copy() when you need an independent patch. See Views vs Copies for the full story. Also clamp your coordinates: a slice past the edge is silently clipped, which can give you an array smaller than you expected.

Flip and rotate

cv2.flip(img, flipCode) mirrors an image. A flipCode of 1 flips around the vertical axis (left and right swap), 0 flips around the horizontal axis (top and bottom swap), and -1 does both, which equals a 180-degree rotation.

Python
mirror = cv2.flip(img, 1)      # like a selfie preview
upside = cv2.flip(img, 0)
both   = cv2.flip(img, -1)

turned = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
# also cv2.ROTATE_180 and cv2.ROTATE_90_COUNTERCLOCKWISE

cv2.rotate handles only multiples of 90 degrees, which is exact: no pixels are interpolated, and a 90-degree turn swaps the height and width. For arbitrary angles you need an affine warp, covered in Translation, Rotation and Affine Transforms. In NumPy the same operations are slicing with negative steps and np.rot90.

Python Crop, flip and rotate with slicing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Run it and check the shapes. The 3 by 4 array becomes 4 by 3 after the rotation, which is why pipelines that rotate phone photos must remember to swap their width and height.

Padding with copyMakeBorder

Sometimes you need to make an image bigger by adding a border: to give a filter room at the edge, to pad a photo to a square before feeding a neural network, or just for a frame. cv2.copyMakeBorder(img, top, bottom, left, right, borderType, value=...) returns a new image with the given number of pixels added on each side.

Python
padded = cv2.copyMakeBorder(img, 20, 20, 30, 30, cv2.BORDER_CONSTANT, value=(0, 0, 0))   # black frame
mirror = cv2.copyMakeBorder(img, 20, 20, 20, 20, cv2.BORDER_REFLECT)                     # mirrored edge
Border type What the new pixels contain
BORDER_CONSTANT A fixed color you pass as value
BORDER_REPLICATE The nearest edge pixel, repeated
BORDER_REFLECT A mirror image of the edge, including the edge pixel (`fedcba
BORDER_REFLECT_101 A mirror without repeating the edge pixel (`gfedcb
BORDER_WRAP The opposite side of the image, as if the picture were tiled

The same border types appear as the borderMode argument of blurs, warps and filters. Limits: padding with a constant adds visible edges that can fool an edge detector, so for filtering prefer reflected borders. To make a letterboxed square image, compute top = (side - h) // 2 and the same for the left, then pad with a neutral color; in NumPy, np.pad does the same job.

Resizing from scratch

To see what resize does, write it. The idea is called inverse mapping: instead of pushing each input pixel to the output (which leaves holes when enlarging), loop over each output pixel, compute which spot in the input it comes from, and read a value there.

For a scale of s = old_size / new_size, output pixel x samples the input at (x + 0.5) * s - 0.5. The 0.5 terms line up the centers of pixels rather than their corners, which is what OpenCV does for its default modes. Nearest neighbor rounds that position to the closest pixel. Bilinear blends the four surrounding pixels, weighted by how close each one is.

Python Nearest and bilinear resize

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Compare the two results. Nearest repeats the original four values in blocks: only 0, 100, 200 and 255 appear. Bilinear invents in-between values and gives a smooth ramp. That is exactly the blocky versus smooth difference you see when enlarging a photo with different flags. The stand-in is a simplified version of the idea, and OpenCV's own code works in fixed-point arithmetic and so may differ from this by one level in places.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. An image has img.shape == (480, 640, 3). Which call makes it half as wide and half as tall?

    dsize is (width, height), so half of 640 by 480 is (320, 240). Passing (240, 320) would transpose the shape, and floats are not valid for dsize; use fx and fy for scale factors.
  2. 2. What does cv2.flip(img, 0) do?

    flipCode 0 flips around the horizontal axis (rows reversed). Code 1 flips left-right, and -1 flips both.
  3. 3. You crop with patch = img[10:60, 20:80] and then draw on patch. What happens to img?

    NumPy slices are views. Use .copy() to get an independent patch.
  4. 4. Which interpolation flag is usually best when you shrink an image a lot?

    INTER_AREA averages the source pixels that map to each output pixel, which avoids the jagged aliasing that other modes give on strong reductions.

Summary

  • cv2.resize(img, (width, height)) takes (width, height), the reverse of img.shape. Alternatively pass fx and fy with dsize=None.
  • Choose the interpolation flag by task: INTER_AREA to shrink, INTER_LINEAR or INTER_CUBIC to enlarge, INTER_NEAREST for masks and labels.
  • Keep the aspect ratio by computing one side from the other, or letterbox to a fixed square.
  • Cropping is slicing img[y1:y2, x1:x2] and returns a view; copy it when you need an independent patch.
  • cv2.flip uses codes 1, 0 and -1; cv2.rotate turns by exact multiples of 90 degrees and swaps height and width.
  • Resizing works by inverse mapping: for every output pixel, compute its source position and sample it (nearest or bilinear).

Next up: rotate by any angle in Translation, Rotation and Affine Transforms.