Logo
C++ Video Processing

Video Sharpening with OpenCV & FFmpeg 7

Harness the power of FFmpeg 7 for high-performance video decoding/encoding, while using OpenCV to apply a spatial sharpening filter frame-by-frame in C++.

Step 1: Project Structure & CMake

Link OpenCV and explicitly enable FFmpeg support

Directory Structure

Prepare a sample blurry video for testing.

cpp-ffmpeg-video/
├── CMakeLists.txt
├── main.cpp # 核心处理代码
└── blurry_input.mp4 # 测试视频

CMake Configuration

cmake_minimum_required(VERSION 3.10)
project(VideoSharpenFFmpeg)

# 寻找 OpenCV,OpenCV 内部会自动链接 FFmpeg
find_package(OpenCV REQUIRED)
include_directories(${OpenCV_INCLUDE_DIRS})

add_executable(sharpen_video main.cpp)
target_link_libraries(sharpen_video ${OpenCV_LIBS})

Step 2: C++ Implementation

Force cv::CAP_FFMPEG backend for robust video I/O

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

int main() {
    // 1. 使用 FFmpeg 后端打开视频流 (cv::CAP_FFMPEG)
    cv::VideoCapture cap("blurry_input.mp4", cv::CAP_FFMPEG);
    if (!cap.isOpened()) {
        std::cerr << "Error: Cannot open video file." << std::endl;
        return -1;
    }

    // 2. 获取原视频的参数 (宽高、帧率)
    int width = static_cast<int>(cap.get(cv::CAP_PROP_FRAME_WIDTH));
    int height = static_cast<int>(cap.get(cv::CAP_PROP_FRAME_HEIGHT));
    double fps = cap.get(cv::CAP_PROP_FPS);
    // 强制使用 H.264 编码器 (依赖 FFmpeg 的 libx264)
    int fourcc = cv::VideoWriter::fourcc('H','2','6','4');

    // 3. 初始化 VideoWriter,同样指定 FFmpeg 后端
    cv::VideoWriter writer("clear_output.mp4", cv::CAP_FFMPEG, fourcc, fps, cv::Size(width, height));

    // 4. 定义拉普拉斯锐化矩阵
    cv::Mat kernel = (cv::Mat_<float>(3, 3) <<
         0, -1,  0,
        -1,  5, -1,
         0, -1,  0);

    cv::Mat frame, sharpened_frame;
    int frame_count = 0;

    // 5. 循环读取每一帧,处理并写入
    while (cap.read(frame)) {
        cv::filter2D(frame, sharpened_frame, -1, kernel);
        writer.write(sharpened_frame);
        frame_count++;
        if (frame_count % 30 == 0) std::cout << "Processed " << frame_count << " frames..." << std::endl;
    }

    cap.release();
    writer.release();
    std::cout << "Success: Video sharpened and saved!" << std::endl;
    return 0;
}

Step 3: Execute

Compile and transform your video

mkdir build && cd buildcmake .. && make -j4./sharpen_video
Processed 30 frames...
Processed 60 frames...
Success: Video sharpened and saved!