乞丐哥的私房菜(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];
      }

结果


相关推荐
CoovallyAIHub1 天前
仿生学突破:SILD模型如何让无人机在电力线迷宫中发现“隐形威胁”
深度学习·算法·计算机视觉
CoovallyAIHub1 天前
从春晚机器人到零样本革命:YOLO26-Pose姿态估计实战指南
深度学习·算法·计算机视觉
CoovallyAIHub1 天前
Le-DETR:省80%预训练数据,这个实时检测Transformer刷新SOTA|Georgia Tech & 北交大
深度学习·算法·计算机视觉
CoovallyAIHub1 天前
强化学习凭什么比监督学习更聪明?RL的“聪明”并非来自算法,而是因为它学会了“挑食”
深度学习·算法·计算机视觉
CoovallyAIHub1 天前
YOLO-IOD深度解析:打破实时增量目标检测的三重知识冲突
深度学习·算法·计算机视觉
端平入洛2 天前
auto有时不auto
c++
哇哈哈20213 天前
信号量和信号
linux·c++
多恩Stone3 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
欧云服务器3 天前
怎么让脚本命令可以同时在centos、debian、ubuntu执行?
ubuntu·centos·debian
智渊AI3 天前
Ubuntu 20.04/22.04 下通过 NVM 安装 Node.js 22(LTS 稳定版)
ubuntu·node.js·vim