numpy
IVP Lab Test Cheatsheet: NumPy, OpenCV, and Matplotlib
Course: Image and Video Processing Lab (EC39028)
Author: Utsab Karan (23EC39028)
1. Advanced NumPy Operations & Array Manipulations
1.1 (n,) vs (1, n) Arrays & Concatenation Traps
shape = (n,)is 1-Dimensional (only hasaxis=0).shape = (1, n)is 2-Dimensional (axis=0is rows,axis=1is columns).
a = np.array([1, 2, 3]) # (3,)
b = np.array([4, 5, 6]) # (3,)
# β TRAP: Concatenating (n,) arrays along axis 0 does NOT stack them as rows!
res = np.concatenate((a, b), axis=0) # Shape: (6,) -> still flat!
# β
To get a 2 x n matrix from 1D arrays:
res = np.vstack((a, b)) # Shape: (2, 3)
res = np.stack((a, b), axis=0) # Shape: (2, 3)
# β
To get an n x 2 matrix (Design Matrix A = [Ix, Iy] for Optical Flow):
A = np.column_stack((a, b)) # Shape: (3, 2)
A = np.stack((a, b), axis=1) # Shape: (3, 2)
1.2 np.stack vs np.concatenate vs np.dstack
np.concatenateNEVER creates a new axis. It glues arrays along an already existing dimension.np.stackALWAYS creates a BRAND NEW axis. (Increases total dimensions by 1).
A = np.zeros((3, 4))
B = np.zeros((3, 4))
# Along axis 0:
np.concatenate((A, B), axis=0).shape # -> (6, 4) [2D matrix: 3+3=6 rows]
np.stack((A, B), axis=0).shape # -> (2, 3, 4) [3D block: new axis at front]
# Along axis 1:
np.concatenate((A, B), axis=1).shape # -> (3, 8) [2D matrix: 4+4=8 cols]
np.stack((A, B), axis=1).shape # -> (3, 2, 4) [3D block: new axis in middle]
# What if axis is omitted? BOTH default to axis=0:
np.concatenate((A, B)).shape # -> (6, 4)
np.stack((A, B)).shape # -> (2, 3, 4)
Stacking Color Channels (R, G, B of shape (H, W)):
# Both produce the exact same 3D color image (H, W, 3):
img_rgb = np.dstack((R, G, B))
img_rgb = np.stack((R, G, B), axis=-1) # axis=-1 means the trailing/last axis
# β TRAP: If you forget axis=-1 in np.stack:
img_bad = np.stack((R, G, B)) # shape: (3, H, W) -> Channels FIRST!
# This breaks plt.imshow and cv2 functions! Always use axis=-1.
1.3 Negative Step Slicing Trap (start : stop : step)
When step is negative (-1), you must count downwards, so start must be > stop!
# β TRAP:
count[3:4:-1, :] # Returns EMPTY [] because 3 is already < 4!
# β
To slice row 4 down to 3:
count[4:2:-1, :] # picks row 4, then row 3
# β
To invert all rows (e.g. BMP bottom-up image inversion):
img_top_down = img[::-1, :]
1.4 Kernel Flipping for 2D Convolution vs. Cross-Correlation
# β TRAP: kernel[:, ::-1] only flips columns (horizontal flip)!
kernel[:, ::-1] == np.flip(kernel, axis=1) == np.fliplr(kernel) # Left <-> Right ONLY
# β
For 2D Spatial Convolution h(-x, -y), you MUST flip BOTH axes (180Β° rotation):
kernel_flipped = kernel[::-1, ::-1] # Slice syntax
kernel_flipped = np.flip(kernel) # np.flip without axis flips ALL dimensions!
1.5 Padding Syntax & Modes (np.pad)
pad_width takes a 2-tuple (before, after) for every axis of the array:
(0, pad_h)on axis 0 means: add0rows to top,pad_hrows to bottom.(0, pad_w)on axis 1 means: add0cols to left,pad_wcols to right.
# For 2D Grayscale:
padded_gray = np.pad(img_gray, ((0, pad_h), (0, pad_w)), mode='constant', constant_values=0)
# For 3D RGB (H, W, 3): MUST include (0, 0) for the 3rd channel axis!
padded_rgb = np.pad(img_rgb, (
(0, pad_h), # rows
(0, pad_w), # cols
(0, 0) # channels (keep exactly 3 channels!)
), mode='constant')
Meaning of mode / border_mode:
'constant'(cv2.BORDER_CONSTANT): Fills with a fixed value (default0= black). Used in FFT zero-padding.- Risk in spatial filtering: Creates artificial dark halo borders around images.
'edge'(cv2.BORDER_REPLICATE): Replicates the nearest boundary pixel outward.- Advantage: Best for spatial filtering/blurring because it prevents dark halos and false edges.
'reflect'(cv2.BORDER_REFLECT): Mirrors pixels across the edge boundary.
1.6 Why We Explicitly Use .astype() Everywhere
uint8Overflow & Underflow (Modulo 256):a = np.array([250], dtype=np.uint8) b = np.array([20], dtype=np.uint8) a + b # -> [14] (270 % 256) -> Bright pixel turns black! b - a # -> [26] (-230 % 256) -> Shadow turns white!Always cast to float before math:
a.astype(float) + b.astype(float).Gradients & Differences Must Hold Negative Numbers:
- Spatial/temporal gradients ($I_x, I_y, I_t = I_{\text{curr}} - I_{\text{prev}}$) have negative values.
cv2.Sobel(image.astype(float), cv2.CV_64F, 1, 0).
Preventing Integer Truncation in Division:
- In Haar wavelets: $\frac{a+b}{2}$. In integer math, $5 // 2 = 2$. Casting to float preserves $2.5$.
Display & Saving Expectations:
- Float images in
plt.imshoware assumed to be in range[0.0, 1.0]. If values are[0, 255], values $> 1.0$ blow out to pure white! - Always finish processing with:
output_image = np.clip(processed, 0, 255).astype(np.uint8)
- Float images in
1.7 np.indices vs. np.meshgrid
np.indices((H, W)): Only needs the shape tuple. Produces integer pixel indices starting at 0:grid_y: Row indices ($0 \dots H-1$)grid_x: Column indices ($0 \dots W-1$)- Perfect for FFT centering mask:
(-1) ** (grid_x + grid_y)and distance maps.
np.meshgrid(ax, ax): Takes explicit 1D coordinate arrays. Allows negative and floating-point values:# Centered Gaussian kernel coordinates with trailing dots (1.0 float literal): ax = np.arange(-size // 2 + 1.0, size // 2 + 1.0) xx, yy = np.meshgrid(ax, ax) kernel = np.exp(-(xx**2 + yy**2) / (2.0 * sigma**2))
1.8 Lookup Tables (LUT) & Array-Based Indexing
Transform entire images in $O(1)$ without any loops:
# Histogram Equalization mapping
lut = np.clip(np.round(cdf * 255), 0, 255).astype(np.uint8)
# Transform entire image directly via array indexing:
equalized_img = lut[input_img] # input_img must be uint8 (0..255)
1.9 Linear Algebra for Optical Flow & Least Squares
Solving $(A^T A) \mathbf{v} = -A^T b$:
ATA = A.T @ A
ATb = A.T @ b
# Check conditioning (Aperture problem)
eigenvalues = np.linalg.eigvals(ATA)
if np.min(eigenvalues) > 0.02:
# np.linalg.solve is faster and more stable than np.linalg.inv!
v = np.linalg.solve(ATA, -ATb)
u, v_comp = v[0, 0], v[1, 0]
1.10 Morphological Masking & Sliding Window Tricks
1. Asymmetric Padding for Kernels with Arbitrary Origins:
If a kernel has shape (kh, kw) and origin (r0, c0) (e.g. $[1, 1]$ with origin at $(0, 0)$):
# Padding needed so kernel origin aligns directly with pixel (r, c):
pad_top = r0
pad_bottom = kh - 1 - r0
pad_left = c0
pad_right = kw - 1 - c0
padded = np.pad(image, ((pad_top, pad_bottom), (pad_left, pad_right)), mode='constant', constant_values=0)
2. Dilation with np.max:
Since $window \in \{0, 255\}$ and $SE \in \{0, 1\}$, element-wise multiplication masks background pixels.
To check if any pixel touches foreground (a “hit”), you can skip if conditions entirely:
# Dilation = local maximum under reflected structuring element
window = padded[r : r + kh, c : c + kw]
output[r, c] = np.max(window * SE_reflected) # yields 255 if any hit, else 0!
3. Erosion with np.sum:
To check if the kernel fits completely inside the foreground (all active $SE$ pixels are $255$):
# Erosion = full fit test via sum
target_sum = 255 * np.sum(SE)
if np.sum(window * SE) == target_sum:
output[r, c] = 255
4. The 2D Convolution / Dilation Slicing Trick (No Index Math):
Instead of $H \times W$ iterations, loop only over the kernel ($kh \times kw$) using the padded image:
# Vectorized Dilation in 5 lines:
pad = ((kh - 1 - r0, r0), (kw - 1 - c0, c0))
padded = np.pad(image, pad, mode='constant', constant_values=0)
dilated = np.zeros_like(image)
for i in range(kh):
for j in range(kw):
if SE[i, j]:
dilated |= padded[kh - 1 - i : kh - 1 - i + H, kw - 1 - j : kw - 1 - j + W]
2. Fourier Transform (np.fft) & Manual fftshift
2.1 Does np.fft.fft2 Require Power-of-2 Padding?
np.fft.fft2works on ANY dimension (odd, even, prime, e.g. $380 \times 364$) without padding!- Only custom Cooley-Tukey Radix-2 implementations require $2^k$ because of recursive halving ($N/2$).
- Built-in padding trick:
np.fft.fft2(image, s=(512, 512))automatically zero-pads to $512 \times 512$.
2.2 How to Do fftshift WITHOUT np.fft.fftshift
Method A: Spatial Domain $(-1)^{x+y}$ Trick (Before FFT)
grid_y, grid_x = np.indices((H, W))
# Multiply spatial image by (-1)^(x+y) before FFT -> output is automatically centered!
centered_F = np.fft.fft2(image * ((-1) ** (grid_x + grid_y)))
Method B: Frequency Domain Quadrant Swapping (After FFT)
def manual_fftshift(F):
hy, hx = F.shape[0] // 2, F.shape[1] // 2
q1 = F[:hy, :hx] # Top-Left
q2 = F[:hy, hx:] # Top-Right
q3 = F[hy:, :hx] # Bottom-Left
q4 = F[hy:, hx:] # Bottom-Right
top = np.concatenate((q4, q3), axis=1) # Swap diagonals
bottom = np.concatenate((q2, q1), axis=1)
return np.concatenate((top, bottom), axis=0)
Method C: One-liner with np.roll:
centered_F = np.roll(F, (F.shape[0] // 2, F.shape[1] // 2), axis=(0, 1))
3. OpenCV (cv2) & Image Saving Best Practices
3.1 Writing & Saving Images (cv2.imwrite vs plt.imsave vs plt.savefig)
import cv2
import matplotlib.pyplot as plt
# 1. ALWAYS clean the array before saving:
save_ready = np.clip(img, 0, 255).astype(np.uint8)
# 2. Saving Grayscale with OpenCV:
cv2.imwrite("output_gray.png", save_ready)
# 3. Saving Color with OpenCV (expects BGR!):
# If your image is currently RGB, convert to BGR first:
save_bgr = cv2.cvtColor(save_ready, cv2.COLOR_RGB2BGR)
cv2.imwrite("output_color.png", save_bgr)
# 4. Saving directly with Matplotlib (no BGR conversion needed):
plt.imsave("output_rgb.png", save_ready)
plt.imsave("spectrum.png", log_mag, cmap="gray")
# 5. Saving a full figure with multiple subplots and titles:
fig, axes = plt.subplots(1, 2, figsize=(8, 4))
axes[0].imshow(img1, cmap="gray")
axes[0].set_title("Input")
axes[1].imshow(img2, cmap="gray")
axes[1].set_title("Output")
plt.tight_layout()
plt.savefig("comparison.png", dpi=150)
plt.close()
3.2 Drawing Motion Vectors (cv2.arrowedLine)
# pt1 and pt2 MUST be integer tuples: (x, y) = (col, row)
pt1 = (int(x), int(y))
pt2 = (int(x + scale * u), int(y + scale * v))
cv2.arrowedLine(canvas_bgr, pt1, pt2, color=(0, 255, 0), thickness=1, tipLength=0.3)
3.3 Video Capture and Encoding (cv2.VideoWriter)
cap = cv2.VideoCapture("input.avi")
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS)
# VideoWriter takes (width, height) in (cols, rows) order!
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter("output.avi", fourcc, fps, (width, height))
while True:
ret, frame = cap.read()
if not ret:
break
# ... annotate frame ...
out.write(frame)
cap.release()
out.release() # Flushes video headers!
4. Matplotlib Multi-Panel & Colorbars
# Flatten 2D axes for easy looping:
fig, axes = plt.subplots(2, 3, figsize=(12, 8))
axes = axes.flatten()
for idx, ax in enumerate(axes):
ax.imshow(images[idx], cmap="gray")
ax.set_title(f"Image {idx+1}")
ax.axis("off")
# Colorbar without squishing subplot aspect ratio:
plt.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
plt.tight_layout()
plt.show()