在 opencv 2DFilter 中使用自定义内核 - 导致崩溃......卷积如何?

Using custom kernel in opencv 2DFilter - causing crash ... convolution how?

我想我今天会在 openCV 中尝试一下(自动)correlation/convolution 并制作我自己的 2D 过滤器内核。

跟随 openCV 的 2D Filter Tutorial I discovered that making your own kernels for openCV's Filter2D 可能 并不那么难。但是,当我尝试使用一个时出现未处理的异常。

此处包含与此问题相关的注释的代码:

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>

using namespace cv;
using namespace std;

int main(int argc, char** argv) {

    //Loading the source image
    Mat src;
    src = imread( "1.png" );

    //Output image of the same size and the same number of channels as src.
    Mat dst;
    //Mat dst = src.clone();   //didn't help...

    //desired depth of the destination image
    //negative so dst will be the same as src.depth()
    int ddepth = -1;        

    //the convolution kernel, a single-channel floating point matrix:
    Mat kernel = imread( "kernel.png" );
    kernel.convertTo(kernel, CV_32F);     //<<not working
    //normalize(kernel, kernel, 1.0, 0.0, 4, -1, noArray());  //doesn't help

    //cout << kernel.size() << endl;  // ... gives 11, 11

    //however, the example from tutorial that does work:
    //kernel = Mat::ones( 11, 11, CV_32F )/ (float)(11*11);

    //default value (-1,-1) here means that the anchor is at the kernel center.
    Point anchor = Point(-1,-1);

    //value added to the filtered pixels before storing them in dst.
    double delta = 0;

    //alright, let's do this...
    filter2D(src, dst, ddepth , kernel, anchor, delta, BORDER_DEFAULT );

    imshow("Source", src);     //<< unhandled exception here
    imshow("Kernel", kernel);
    imshow("Destination", dst);
    waitKey(1000000);

    return 0;
}

如您所见,使用教程内核工作正常,但我的图像会使程序崩溃,我尝试更改位深度、规范化、检查大小和大量注释块以查看它在哪里失败,但还没破解

图像是,'1.png':

还有我想要的内核'kernel.png':

我正在尝试查看是否可以在 dst 中的聚光灯所在的位置获得热点(我选择的内核 聚光灯)。我知道还有其他方法可以做到这一点,但我很想知道将聚光灯与自身进行卷积的效果如何。 (我认为这叫做自相关?)

直接提问:

在此先感谢您的帮助:)

应该发布断言错误,这将帮助其他人回答您,而不是质疑崩溃的原因。无论如何,我已经在下面发布了卷积 filter2D 的可能错误和解决方案。

错误 1:

OpenCV 错误:cv::countNo 中的断言失败 (src.channels() == 1 && func != 0) nZero,文件 C:\builds_4_PackSlave-win32-vc12-shared\opencv\modules\core\src\st at.cpp,第 549 行

解决方案:您的输入图像和内核应该是灰度的。您可以在 imread 中使用标志 0。 (例如 cv::imread("kernel.png",0) 将图像读取为灰度。)如果要将不同的内核应用于不同的通道,请将图像拆分为单独的使用 split() 为平面上色并单独处理它们。

除了上述可能崩溃的错误,我没有看到任何其他内容。内核大小应该是奇数,您的内核映像是 11X11,这很好。如果仍然崩溃,请提供更多信息以帮助您解决问题。