Logo
C++ Computer Vision

C++ OpenCV: Image Sharpening

Implement the spatial convolution filter in high-performance C++ using CMake. Learn how to define Mat kernels and apply filter2D natively.

Step 1: Project Structure & CMake

Setup the C++ workspace and link OpenCV libraries

Directory Structure

Create the following files in your new C++ project directory:

cpp-sharpen-app/
├── CMakeLists.txt # 构建脚本
├── main.cpp # C++ 源码
└── input_blurry.jpg # 测试原图

CMake Configuration

The CMake script strictly requires the OpenCV package to compile.

cmake_minimum_required(VERSION 3.10)
project(ImageSharpen)

# 寻找 OpenCV 库
find_package(OpenCV REQUIRED)
include_directories(${OpenCV_INCLUDE_DIRS})

# 编译可执行文件
add_executable(sharpen_app main.cpp)
target_link_libraries(sharpen_app ${OpenCV_LIBS})

Step 2: C++ Implementation

Using cv::Mat and cv::filter2D to process the image

main.cpp
#include <opencv2/opencv.hpp>
#include <iostream>

int main(int argc, char** argv) {
    // 1. 读取原图
    cv::Mat img = cv::imread("input_blurry.jpg");
    if (img.empty()) {
        std::cerr << "Error: Could not read image." << std::endl;
        return -1;
    }

    // 2. 定义拉普拉斯衍生锐化卷积核 (3x3)
    cv::Mat kernel = (cv::Mat_<float>(3, 3) <<
         0, -1,  0,
        -1,  5, -1,
         0, -1,  0);

    // 3. 应用空间滤波 (ddepth = -1 保持与原图相同的深度)
    cv::Mat sharpened;
    cv::filter2D(img, sharpened, img.depth(), kernel);

    // 4. 保存并显示结果
    cv::imwrite("output_sharp_cpp.jpg", sharpened);
    std::cout << "Success: Sharpened image saved." << std::endl;

    return 0;
}

Step 3: Build & Execution

Generate Makefile, compile the code, and run the executable

Execute via Terminal

Run these commands in your project root to build and execute the C++ application.

mkdir build && cd buildcmake ..make -j4cp ../input_blurry.jpg . # 拷贝测试图./sharpen_app
Success: Sharpened image saved.