Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 54 ยท Image Processing

Arithmetic, Bitwise Ops and Masking

Learn why cv2.add saturates but numpy wraps, how addWeighted blends images, and how inRange and bitwise_and build masks. Every idea is rebuilt in numpy.

Once an image is an array, you can do arithmetic on it: add two images, blend them, brighten one, cut a shape out of another. OpenCV has dedicated functions for this, and they behave differently from the same operations in plain numpy in one crucial way: what happens when a value leaves the 0..255 range. This lesson covers that difference, weighted blending, bitwise operations, and masks, which together let you select, combine and overlay parts of images.

As in the rest of this track, cv2 cannot run on this site. OpenCV calls are shown read-only, and each idea has a numpy version that runs live. If you need a refresher on data types, see Images Are NumPy Arrays.

Saturation versus wraparound

An 8-bit pixel holds 0 to 255. What is 200 + 100? In cv2.add, the result is saturated to 255, the nearest valid value. In numpy, uint8 arithmetic wraps around modulo 256, so the answer is 44. For images the OpenCV behavior is the sensible one: a bright pixel made brighter stays white and does not suddenly turn dark.

Python
import cv2
import numpy as np

a = np.array([[200]], dtype=np.uint8)
b = np.array([[100]], dtype=np.uint8)

print(cv2.add(a, b))      # [[255]]  saturated
print(a + b)              # [[44]]   wrapped
print(cv2.subtract(b, a)) # [[0]]    saturated at the bottom
print(b - a)              # [[156]]  wrapped

Both images must have the same size and type for cv2.add and cv2.subtract. Adding a bare number is a trap: OpenCV may read it as a scalar that fills only the first channel, so cv2.add(img, 50) can brighten just blue in a BGR image. To brighten every channel, add a full array of the same shape (for example np.full_like(img, 50)) or use cv2.convertScaleAbs, covered in Data Types, Ranges and Saturation.

You can reproduce saturating arithmetic in numpy by doing the math in a wider type, then clipping and converting back.

Python cv2.add versus numpy +

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.

The last line is cv2.absdiff, which is often what you want when comparing two images: the absolute difference never wraps, and it does not depend on which image is first.

Blending with addWeighted

A cross-fade between two images is a weighted sum: dst = src1 * alpha + src2 * beta + gamma. OpenCV does this in one call, rounding and saturating the result:

Python
blend = cv2.addWeighted(img1, 0.7, img2, 0.3, 0)

For a plain blend, choose alpha + beta = 1, so overall brightness is preserved. A gamma adds a constant brightness offset. With alpha above 1 and beta 0, the same function is a contrast boost. Both images must match in size and type.

Python addWeighted rebuilt in numpy

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.

As alpha falls from 1 to 0 the output slides from the first image to the second. The last row shows saturation again: values pushed past 255 stop at 255.

Bitwise operations and masks

Bitwise functions (cv2.bitwise_and, bitwise_or, bitwise_xor, bitwise_not) work on the individual bits of each pixel value. Their most useful job is with masks. A mask is a single-channel 8-bit image the same size as the picture, where nonzero means "this pixel is selected" and 0 means "ignore it". Masks are the standard way to restrict an operation to a region, and many OpenCV functions (bitwise_and, calcHist, mean, copyTo, add, ...) accept one through a mask= argument.

Python
selected = cv2.bitwise_and(img, img, mask=mask)

Anding an image with itself changes nothing where the mask is on, and the mask argument sets everything else to black. That makes it a "keep only this region" tool. bitwise_not flips every bit, so on a 0/255 mask it inverts the mask.

Selecting a color with inRange

cv2.inRange(src, lower, upper) returns a mask: 255 where every channel lies between the lower and upper bounds (both inclusive), and 0 otherwise. It is the core of color detection, usually applied to an HSV image, because hue separates color from brightness (see Color Spaces):

Python
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, (100, 120, 70), (130, 255, 255))   # blues
only_blue = cv2.bitwise_and(img, img, mask=mask)

Select, then combine

inRange Builds a 0/255 mask from color bounds.
Mask Nonzero means keep, zero means ignore.
bitwise_and Keeps only the masked pixels.
bitwise_not Inverts a mask.

The same mask can feed many functions through mask=.

1 / 2

The example makes a tiny BGR image with colored blocks, selects the blue ones with a range test, and applies the mask. Remember the OpenCV channel order is blue, green, red.

Python inRange and bitwise_and by hand

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.

The mask is 255 on the three blue columns only. The masked image keeps those pixels and sets the red and green ones to black. The final line shows that a mask and its inverse partition the image exactly, so combining the two pieces restores the original. The numpy trick img * (mask[..., None] > 0) shows how a mask broadcasts over the three channels, and img[mask > 0] is another way to pick the selected pixels, as in Accessing and Modifying Pixels.

Overlaying a logo with a mask

Putting a small image on top of a larger one is a classic mask exercise. The recipe is: take the region of interest (ROI) where the logo will go, black out the logo's shape in the ROI using the inverted mask, keep only the logo's own pixels using the mask, and add the two pieces (they cannot overlap, so the saturating add is safe).

Python
roi = bg[y:y + h, x:x + w]
bg_part = cv2.bitwise_and(roi, roi, mask=cv2.bitwise_not(mask))
fg_part = cv2.bitwise_and(logo, logo, mask=mask)
bg[y:y + h, x:x + w] = cv2.add(bg_part, fg_part)
Python Overlay a shape using a mask

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.

The diamond appears over the stripes, and the changed-pixel count equals the number of pixels in the mask. In real OpenCV code you would more often use a logo with an alpha channel, or addWeighted over the ROI for a semi-transparent watermark, but the mask-and-combine pattern stays the same.

Pitfalls

  • Operands to cv2.add, cv2.bitwise_and and friends must match in size and type; a 3-channel image and a 1-channel mask do not mix except through the mask= argument.
  • Masks must be 8-bit single-channel. A mask with values 0 and 1 works for mask= (nonzero counts), but if you want to display it, multiply by 255.
  • a + b in numpy wraps, so do not use it on raw uint8 images unless you want modular arithmetic.
  • inRange bounds are inclusive and apply per channel; for hue, which wraps around (red sits at both ends), combine two ranges with cv2.bitwise_or.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Two uint8 arrays hold 200 and 100. What do cv2.add and numpy a + b give?

    cv2.add saturates at 255, while numpy uint8 addition wraps around modulo 256 and gives 44.
  2. 2. In cv2.addWeighted(a, 0.7, b, 0.3, 0), what does the last argument gamma do?

    The result is aalpha + bbeta + gamma, so gamma is a constant offset, usually 0 or a small brightness shift.
  3. 3. What does cv2.inRange return?

    inRange creates a single-channel mask. You usually pass it to bitwise_and or another function through the mask argument.
  4. 4. How do you keep only the pixels of img where mask is nonzero?

    Anding the image with itself leaves values unchanged, and the mask argument zeroes everything outside the selection.

Summary

  • cv2.add and cv2.subtract saturate to 0..255, while numpy uint8 arithmetic wraps around; widen to int16, clip and convert back to imitate OpenCV.
  • cv2.addWeighted computes src1*alpha + src2*beta + gamma, rounded and saturated; use alpha + beta = 1 for a cross-fade.
  • A mask is an 8-bit single-channel image where nonzero means selected; many functions take it through mask=.
  • cv2.inRange makes a mask from per-channel bounds, usually in HSV; bitwise_and with a mask keeps only the selected pixels, and bitwise_not inverts a mask.
  • Overlays combine a masked ROI with a masked logo.

Next up: Gradients, Sobel and Laplacian.