卷积滤镜2D

时间:2018-05-27 11:36:37

标签: c++ opencv math image-processing signal-processing

我试图在C ++中为图像创建卷积滤镜。 我正在使用OpenCV库来操作我的图像。

但我的过滤器无法正常工作。

首次尝试:

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

using namespace cv;
using namespace std;


/*
  filtre de convolution
*/

void filterConvolutionBlack(String pathImage, std::vector<std::vector<int>> filter) {
   Mat src;
   int ii = 0, jj = 0, value = 0;

   // Image source
   src = imread(pathImage, IMREAD_GRAYSCALE);

   // Image destination
   Mat dest;
   dest = src.clone();

   // On cherche le centre de la matrice
   int filterCenterX = (int)filter[0].size() / 2; // Colonne
   int filterCenterY = (int)filter.size() / 2; // Ligne

   // On parcours les lignes de l'image
   for (int i = 0; i < src.rows; ++i) {
       // On parcours les colonnes de l'image
       for (int j = 0; j < src.cols; ++j) {
           value = 0;
           // On parcours les lignes du filtre
           for (int fi = 0; fi < (int)filter.size(); ++fi) {
               // On parcours les colonnes du filtre
               for (int fj = 0; fj < (int)filter[0].size(); ++fj) {
                   // On calcul la position du pixel à modifier
                   ii = i + (fi - filterCenterY);
                   jj = j + (fj - filterCenterX);

                   // On vérifie que les postions ne sont pas hors limite
                   if (ii >= 0 && ii < src.rows && jj >= 0 && jj < src.cols) 
                   {
                       value += (int)src.at<uchar>(ii, jj) * filter[fi][fj];
                   }
               }
           }
           dest.at<uchar>(i, j) = value;
       }
   }
   imshow("Filter", dest);
 }

 int main(int argc, char **argv)
 {
   String pathImage = "loutre.png";

   // On creer un filtre 3*3
   std::vector<std::vector<int>> filter;
   filter.resize(3, std::vector<int>(3, 0));
   filter = {
       {1,1,1},
       {1,-8,1},
       {1,1,1}
   };

   filterConvolutionBlack(pathImage, filter);

   waitKey(0);

   return EXIT_SUCCESS;
 }

dest变量是最终结果,src变量是基本图像。

目前的结果:

Result

但是,预期的结果是:

expected

我认为问题来自数组索引,但我不确定。

0 个答案:

没有答案
相关问题