Logo
Computer Vision Tutorial

Make Blurry Images Clear with Python + OpenCV

A complete guide to enhancing image clarity using OpenCV and Python. Learn how to apply convolution kernels to restore edge details in blurry photos.

Step 1: Project Structure & Dependencies

Setup your workspace and install required pip packages

Directory Structure

Create a new folder and set up the following files:

opencv-sharpen-project/
├── main.py # 核心代码
├── requirements.txt # 依赖声明
├── input_blurry.jpg # 你的模糊原图
└── output_sharp.jpg # 生成的清晰图片

Install Dependencies

We only need OpenCV and NumPy for this task.

requirements.txt:
opencv-python==4.8.1.78
numpy==1.26.2
Install Command:
pip install -r requirements.txt

Step 2: Core Algorithm & Code

Using a sharpening kernel with cv2.filter2D

How does Sharpening Work?

We use a specific 3x3 matrix called a kernel: [[0, -1, 0], [-1, 5, -1], [0, -1, 0]]. The center weight (5) amplifies the target pixel, while the negative surrounding weights (-1) subtract the blurred background. This effectively increases contrast at the edges, making the image appear 'sharper'.

main.py
import cv2
import numpy as np

def sharpen_image(image_path, output_path):
    # 1. 读取原图 (Read the image)
    img = cv2.imread(image_path)
    if img is None:
        print(f"Error: 找不到图片 {image_path},请检查路径!")
        return

    # 2. 定义锐化卷积核 (Define the sharpening kernel)
    # 中心像素权重为 5,周围四个像素权重为 -1
    kernel = np.array([
        [ 0, -1,  0],
        [-1,  5, -1],
        [ 0, -1,  0]
    ], dtype=np.float32)

    # 3. 应用 filter2D 函数进行 2D 卷积 (Apply 2D filter)
    # 第二个参数 -1 表示输出图像与输入图像具有相同的深度 (数据类型)
    sharpened = cv2.filter2D(img, -1, kernel)

    # 4. 保存结果 (Save result)
    cv2.imwrite(output_path, sharpened)
    print(f"Success: 锐化完成!结果已保存至 {output_path}")

if __name__ == "__main__":
    # 执行函数,指定输入与输出路径
    sharpen_image('input_blurry.jpg', 'output_sharp.jpg')

Step 3: Execute & Verification

Run the python script and compare the outputs

1. Run the script

Ensure your blurry image is placed in the folder and named correctly, then run the python file.

Terminal:
python main.py
Expected Output:
Success: 锐化完成!结果已保存至 output_sharp.jpg
2. Advanced Tuning

If the image looks too harsh or noisy, try a softer kernel or apply a slight Gaussian blur before sharpening to reduce noise.

Stronger Kernel Variant:
kernel = np.array(
  [[-1, -1, -1],
   [-1,  9, -1],
   [-1, -1, -1]]
)