Advertisement
jack06215

[OpenCV] conv2

Jul 7th, 2020
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.28 KB | None | 0 0
  1. enum ConvolutionType
  2. {
  3.     /* Return the full convolution, including border */
  4.     CONVOLUTION_FULL,
  5.  
  6.     /* Return only the part that corresponds to the original image */
  7.     CONVOLUTION_SAME,
  8.  
  9.     /* Return only the submatrix containing elements that were not influenced by the border */
  10.     CONVOLUTION_VALID
  11. };
  12.  
  13. void conv2(const cv::Mat &img, cv::Mat& dest, const cv::Mat& kernel, ConvolutionType type)
  14. {
  15.     cv::Mat source = img;
  16.     if (type == CONVOLUTION_FULL)
  17.     {
  18.         source = cv::Mat();
  19.         const int additionalRows = kernel.rows - 1, additionalCols = kernel.cols - 1;
  20.         copyMakeBorder(img, source, (additionalRows + 1) / 2, additionalRows / 2, (additionalCols + 1) / 2, additionalCols / 2, cv::BORDER_CONSTANT, cv::Scalar(0));
  21.     }
  22.  
  23.     cv::Point anchor(cv::Point(-1, -1));
  24.     int borderMode = cv::BORDER_CONSTANT;
  25.     filter2D(source, dest, img.depth(), kernel.t(), anchor, 0, borderMode);
  26.  
  27.     if (type == CONVOLUTION_VALID)
  28.     {
  29.         dest = dest.colRange((kernel.cols - 1) / 2, dest.cols - kernel.cols / 2)
  30.             .rowRange((kernel.rows - 1) / 2, dest.rows - kernel.rows / 2);
  31.     }
  32. }
  33.  
  34. int main(void)
  35. {
  36.     // ....
  37.     cv::Mat imgMat = cv::imread("sample.jpg", CV_LOAD_IMAGE_COLOR);
  38.     cv::Mat gau_mask = cv::getGaussianKernel(7, 1.5, CV_32F);
  39.     conv2(imgMat_bw, imgMat_bw, gau_mask, CONVOLUTION_SAME);
  40.    
  41.     return 0;
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement