乞丐哥的私房菜(Ubuntu OpenCV篇——Image Processing 节 之 Out-of-focus Deblur Filter 失焦去模糊滤波器 滤镜)

  • 操作系统:手机安装 Termux ,Termux 内安装 ubuntu
    • Termux 0.119.0-beta.3
    • 内嵌 ubuntu 24.04
  • 编译器:GNU g++ 14.2.0
  • 编辑器:Emacs 29.3
  • OpenCV:4.13.0

目标

  • 什么是降解图像模型
  • 失焦图像的 PSF 是什么
  • 如何恢复模糊的图像
  • 什么是维纳过滤器

理论

什么是退化/降级图像模型

以下是频域表示中图像退化的数学模型:
S=H⋅U+NS = H\cdot U + NS=H⋅U+N

其中 S 是模糊(退化)图像的光谱,U 是原始真实(未退化)图像的光谱,H 是点扩散函数(PSF)的频率响应,N 是加性噪声(干扰)的频谱

圆形 PSF 是失焦畸变的良好近似值。这样的 PSF 仅由一个参数指定 - 半径 R 。本工作中使用了圆形 PSF

如何恢复模糊的图像

恢复(去模糊)的目的是获得原始图像的估计值。频域中的恢复公式为:
U′=Hw⋅SU' = H_w\cdot SU′=Hw⋅S

其中 U′U'U′ 是原始图像 UUU 的估计光谱,HwH_wHw 是恢复过滤器,例如,维纳过滤器

什么是维纳过滤器

维纳滤镜/滤波器是一种恢复模糊图像的方法。假设PSF是真实对称信号,原始真实图像的功率谱和噪声未知,那么简化的维纳公式为:
Hw=H∣H∣2+1SNR H_w = \frac{H}{|H|^2+\frac{1}{SNR}} Hw=∣H∣2+SNR1H

其中 SNRSNRSNR 为信噪比,为了通过维纳滤光片恢复失焦图像,它需要知道 SNRSNRSNR 和 RRR 圆的 PSF

源代码

cpp 复制代码
    
  #include <iostream>
  #include "opencv2/highgui.hpp"
  #include "opencv2/imgproc.hpp"
  #include "opencv2/imgcodecs.hpp"

  using namespace cv;
  using namespace std;

  void help();
  void calcPSF(Mat& outputImg, Size filterSize, int R);
  void fftshift(const Mat& inputImg, Mat& outputImg);
  void filter2DFreq(const Mat& inputImg, Mat& outputImg, const Mat& H);
  void calcWnrFilter(const Mat& input_h_PSF, Mat& output_G, double nsr);

  const String keys =
    "{help h usage ? |             | print this message   }"
    "{image          |original.jpg | input image name     }"
    "{R              |5           | radius               }"
    "{SNR            |100         | signal to noise ratio}"
    ;

  int main(int argc, char *argv[])
  {
    help();
    CommandLineParser parser(argc, argv, keys);
    if (parser.has("help"))
      {
        parser.printMessage();
        return 0;
      }

    int R = parser.get<int>("R");
    int snr = parser.get<int>("SNR");
    string strInFileName = parser.get<String>("image");
    samples::addSamplesDataSearchSubDirectory("doc/tutorials/imgproc/out_of_focus_deblur_filter/images");

    if (!parser.check())
      {
        parser.printErrors();
        return 0;
      }

    Mat imgIn;
    imgIn = imread(samples::findFile( strInFileName ), IMREAD_GRAYSCALE);
    if (imgIn.empty()) //check whether the image is loaded or not
      {
        cout << "ERROR : Image cannot be loaded..!!" << endl;
        return -1;
      }

    Mat imgOut;

    // it needs to process even image only
    Rect roi = Rect(0, 0, imgIn.cols & -2, imgIn.rows & -2);

    //Hw calculation (start)
    Mat Hw, h;
    calcPSF(h, roi.size(), R);
    calcWnrFilter(h, Hw, 1.0 / double(snr));
    //Hw calculation (stop)

    // filtering (start)
    filter2DFreq(imgIn(roi), imgOut, Hw);
    // filtering (stop)

    imgOut.convertTo(imgOut, CV_8U);
    normalize(imgOut, imgOut, 0, 255, NORM_MINMAX);
    imshow("Original", imgIn);
    imshow("Debluring", imgOut);
    imwrite("result.jpg", imgOut);
    waitKey(0);
    return 0;
  }

  void help()
  {
    cout << "2018-07-12" << endl;
    cout << "DeBlur_v8" << endl;
    cout << "You will learn how to recover an out-of-focus image by Wiener filter" << endl;
  }

  void calcPSF(Mat& outputImg, Size filterSize, int R)
  {
    Mat h(filterSize, CV_32F, Scalar(0));
    Point point(filterSize.width / 2, filterSize.height / 2);
    circle(h, point, R, 255, -1, 8);
    Scalar summa = sum(h);
    outputImg = h / summa[0];
  }

  void fftshift(const Mat& inputImg, Mat& outputImg)
  {
    outputImg = inputImg.clone();
    int cx = outputImg.cols / 2;
    int cy = outputImg.rows / 2;
    Mat q0(outputImg, Rect(0, 0, cx, cy));
    Mat q1(outputImg, Rect(cx, 0, cx, cy));
    Mat q2(outputImg, Rect(0, cy, cx, cy));
    Mat q3(outputImg, Rect(cx, cy, cx, cy));
    Mat tmp;
    q0.copyTo(tmp);
    q3.copyTo(q0);
    tmp.copyTo(q3);
    q1.copyTo(tmp);
    q2.copyTo(q1);
    tmp.copyTo(q2);
  }

  void filter2DFreq(const Mat& inputImg, Mat& outputImg, const Mat& H)
  {
    Mat planes[2] = { Mat_<float>(inputImg.clone()), Mat::zeros(inputImg.size(), CV_32F) };
    Mat complexI;
    merge(planes, 2, complexI);
    dft(complexI, complexI, DFT_SCALE);

    Mat planesH[2] = { Mat_<float>(H.clone()), Mat::zeros(H.size(), CV_32F) };
    Mat complexH;
    merge(planesH, 2, complexH);
    Mat complexIH;
    mulSpectrums(complexI, complexH, complexIH, 0);

    idft(complexIH, complexIH);
    split(complexIH, planes);
    outputImg = planes[0];
  }

  void calcWnrFilter(const Mat& input_h_PSF, Mat& output_G, double nsr)
  {
    Mat h_PSF_shifted;
    fftshift(input_h_PSF, h_PSF_shifted);
    Mat planes[2] = { Mat_<float>(h_PSF_shifted.clone()), Mat::zeros(h_PSF_shifted.size(), CV_32F) };
    Mat complexI;
    merge(planes, 2, complexI);
    dft(complexI, complexI);
    split(complexI, planes);
    Mat denom;
    pow(abs(planes[0]), 2, denom);
    denom += nsr;
    divide(planes[0], denom, output_G);
  }

解释说明

  • 失焦图像恢复算法包括PSF生成、维纳滤波器生成和频域模糊图像滤波:

    cpp 复制代码
      // it needs to process even image only
      Rect roi = Rect(0, 0, imgIn.cols & -2, imgIn.rows & -2);
    
      //Hw calculation (start)
      Mat Hw, h;
      calcPSF(h, roi.size(), R);
      calcWnrFilter(h, Hw, 1.0 / double(snr));
      //Hw calculation (stop)
    
      // filtering (start)
      filter2DFreq(imgIn(roi), imgOut, Hw);
      // filtering (stop)
  • 函数 calcPSF() 根据输入参数半径 R 形成圆形 PSF

    cpp 复制代码
      void calcPSF(Mat& outputImg, Size filterSize, int R)
      {
        Mat h(filterSize, CV_32F, Scalar(0));
        Point point(filterSize.width / 2, filterSize.height / 2);
        circle(h, point, R, 255, -1, 8);
        Scalar summa = sum(h);
        outputImg = h / summa[0];
      }
  • 根据上述公式,函数 calcWnrFilter() 合成简化的维纳滤波器 HwH_wHw

    cpp 复制代码
      void calcWnrFilter(const Mat& input_h_PSF, Mat& output_G, double nsr)
      {
        Mat h_PSF_shifted;
        fftshift(input_h_PSF, h_PSF_shifted);
        Mat planes[2] = { Mat_<float>(h_PSF_shifted.clone()), Mat::zeros(h_PSF_shifted.size(), CV_32F) };
        Mat complexI;
        merge(planes, 2, complexI);
        dft(complexI, complexI);
        split(complexI, planes);
        Mat denom;
        pow(abs(planes[0]), 2, denom);
        denom += nsr;
        divide(planes[0], denom, output_G);
      }
  • 函数 fftshift() 重新排列 PSF。这段代码只是从离散傅里叶变换教程中复制的:

    cpp 复制代码
      void fftshift(const Mat& inputImg, Mat& outputImg)
      {
        outputImg = inputImg.clone();
        int cx = outputImg.cols / 2;
        int cy = outputImg.rows / 2;
        Mat q0(outputImg, Rect(0, 0, cx, cy));
        Mat q1(outputImg, Rect(cx, 0, cx, cy));
        Mat q2(outputImg, Rect(0, cy, cx, cy));
        Mat q3(outputImg, Rect(cx, cy, cx, cy));
        Mat tmp;
        q0.copyTo(tmp);
        q3.copyTo(q0);
        tmp.copyTo(q3);
        q1.copyTo(tmp);
        q2.copyTo(q1);
        tmp.copyTo(q2);
      }
  • 函数filter2DFreq() 过滤频域中的模糊图像:

    cpp 复制代码
      void filter2DFreq(const Mat& inputImg, Mat& outputImg, const Mat& H)
      {
        Mat planes[2] = { Mat_<float>(inputImg.clone()), Mat::zeros(inputImg.size(), CV_32F) };
        Mat complexI;
        merge(planes, 2, complexI);
        dft(complexI, complexI, DFT_SCALE);
    
        Mat planesH[2] = { Mat_<float>(H.clone()), Mat::zeros(H.size(), CV_32F) };
        Mat complexH;
        merge(planesH, 2, complexH);
        Mat complexIH;
        mulSpectrums(complexI, complexH, complexIH, 0);
    
        idft(complexIH, complexIH);
        split(complexIH, planes);
        outputImg = planes[0];
      }

结果


相关推荐
ZhouDevin1 小时前
算法论文/数据集3——CLD(TMLR2025)压缩训练集,仅保留对验证集有益的样本
人工智能·深度学习·算法·计算机视觉
码匠许师傅1 小时前
【设计模式精讲】14.外观模式(Facade)
c++·设计模式·uml·外观模式
xxwxx__3 小时前
C++ list 深度解析:从使用原理到模拟实现
开发语言·c++·list
Chester_19993 小时前
CSP202303C.LDAP
开发语言·c++·蓝桥杯·stl
j7~4 小时前
【C++】《unordered系列关联式容器以及哈希底层、哈希冲突、闭散列与开散列完整解析》
c++·哈希算法·开散列·闭散列·unordered_map·unordered_set·哈希底层结构
2402_882893865 小时前
封装红黑树实现map和set —— 从源码到模拟实现
c++·set·map
飞Link6 小时前
动作方法中的分割与过度分割方法全解析(含代码实战与踩坑案例)
人工智能·python·算法·计算机视觉
江畔柳前堤6 小时前
具身智能全景深度指南(2026年9月版):从“会聊天的AI“到“能干活的机器“
大数据·javascript·图像处理·人工智能·分布式·智慧城市·原型模式
神仙别闹6 小时前
基于C++ MFC 实现的智慧公交系统
开发语言·c++·mfc
dear_bi_MyOnly7 小时前
函数模块化:企业级项目高效之道
c++·后端·学习