Learning/IVP/Session 02
Session 02

Image Arithmetic

Pixel-level arithmetic operations: addition, subtraction, and multiplication between images.


Learning Objectives

  • Add two images together and observe blending
  • Subtract images to highlight differences
  • Multiply pixel values to boost contrast

Image Addition

Adding two images blends them together. Images must be the same size and type. Convert to float64 first to avoid integer overflow, then clip back to [0, 255].

Ex2_1 — Add two imagesPython
import cv2
import numpy as np

img1 = cv2.cvtColor(cv2.imread('image1.jpg'), cv2.COLOR_BGR2RGB).astype(np.float64)
img2 = cv2.cvtColor(cv2.imread('image2.jpg'), cv2.COLOR_BGR2RGB).astype(np.float64)

# Resize img2 to match img1 dimensions
img2_resized = cv2.resize(img2, (img1.shape[1], img1.shape[0]))

result = np.clip(img1 + img2_resized, 0, 255).astype(np.uint8)

Image Subtraction

Subtracting one image from another reveals the difference between them. Useful for detecting changes or motion. Values can go negative, so work in float64 and take the absolute value or clip.

Ex2_2 — Subtract imagesPython
img1_f = img1.astype(np.float64)
img2_f = img2_resized.astype(np.float64)

# Absolute difference
diff = np.abs(img1_f - img2_f).astype(np.uint8)

# Contrast boost (power 0.5)
contrast = np.uint8(np.clip(diff.astype(np.float64) ** 0.5 * 16, 0, 255))

Image Multiplication

Multiplying an image by itself (or a scalar) boosts brighter pixels more than darker ones. This increases contrast non-linearly. Always convert to float64 and normalize before multiplying.

Ex2_3 — Multiply image by itselfPython
img_f = img1.astype(np.float64) / 255.0

# Multiply image by itself 4 times
result = np.clip(img_f ** 4, 0, 1)
result_uint8 = np.uint8(result * 255)