Image smoothing reduces pixel-to-pixel variation before a vision pipeline tries to threshold, find edges, or measure contours. In OpenCV, Gaussian blur is a common first pass for reducing sensor noise or small texture that would otherwise turn into broken masks and noisy edge maps.
Gaussian blur uses an odd-sized kernel around each pixel and weights nearby pixels with a Gaussian curve. A larger kernel removes more detail, while a zero sigma lets OpenCV derive the standard deviation from the chosen kernel size.
Blurring also softens true boundaries, so keep the kernel just large enough for the downstream operation. The smoke test writes a blurred image and prints a high-frequency score based on grayscale Laplacian variance, which should drop after smoothing.
Steps to blur an image with OpenCV:
- Place the source image at input/scene.png.
Use an image format supported by cv2.imread(). A noisy photo or generated test scene makes the smoothing effect easier to inspect.
- Create blur_image.py.
- blur_image.py
#!/usr/bin/env python3 import argparse from pathlib import Path import cv2 import numpy as np def odd_positive(value: str) -> int: kernel_size = int(value) if kernel_size < 1 or kernel_size % 2 == 0: raise argparse.ArgumentTypeError("kernel size must be a positive odd integer") return kernel_size def high_frequency_score(image: np.ndarray) -> float: gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) return float(cv2.Laplacian(gray, cv2.CV_64F).var()) parser = argparse.ArgumentParser(description="Apply Gaussian blur to an image with OpenCV.") parser.add_argument("input_image", type=Path) parser.add_argument("output_image", type=Path) parser.add_argument("--kernel", type=odd_positive, default=9) parser.add_argument("--sigma", type=float, default=0.0) args = parser.parse_args() image = cv2.imread(str(args.input_image), cv2.IMREAD_COLOR) if image is None: raise SystemExit(f"could not read image: {args.input_image}") blurred = cv2.GaussianBlur(image, (args.kernel, args.kernel), args.sigma) args.output_image.parent.mkdir(parents=True, exist_ok=True) if not cv2.imwrite(str(args.output_image), blurred): raise SystemExit(f"could not write image: {args.output_image}") before_score = high_frequency_score(image) after_score = high_frequency_score(blurred) print(f"input: {args.input_image}") print(f"kernel: {args.kernel}x{args.kernel}") print(f"sigma: {args.sigma:.1f}") print(f"high-frequency score before: {before_score:.2f}") print(f"high-frequency score after: {after_score:.2f}") print(f"output: {args.output_image}")
- Run Gaussian blur and write the output image.
$ python3 blur_image.py input/scene.png output/scene-blur.png --kernel 9 --sigma 0 input: input/scene.png kernel: 9x9 sigma: 0.0 high-frequency score before: 1283.60 high-frequency score after: 17.46 output: output/scene-blur.png
--kernel must be a positive odd integer. Increase it when small texture remains, or lower it when edges needed by thresholding or contour detection become too soft.
- Verify that the blurred output can be reopened.
$ python3 -c 'import cv2; image = cv2.imread("output/scene-blur.png"); print(image.shape)' (480, 720, 3)The shape confirms a three-channel image with the same height and width as the source. The high-frequency score should be lower after blurring; if it rises or stays unchanged, check that the output path points to the newly written file.
- Remove blur_image.py after moving the blur operation into project code.
$ rm blur_image.py
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.