OpenCV离焦模糊与自定义内核?

时间:2011-10-18 17:14:34

标签: opencv kernel blur

我想模拟散焦模糊,图像中每个像素的强度为:

对于给定半径r,

1 /(pi * r ^ 2),如果像素在sqrt(x ^ 2 + y ^ 2)内,则为0,如果不是 (有关更好的解释,请参阅代码)

这给出了圆形的模糊/卷积核。 我尝试在opencv中做到这一点没有运气:opencv只是“像素化”我的图像的边缘: testimage http://www.bilderkiste.org/show/original/1131895735815/test_out.jpg

我无法弄清楚为什么会发生这种情况,到目前为止这是我的代码:

//includes. then:
using namespace std;
#define KERNELLENGTH 3
#define PI 3.14159265
int main() {
    IplImage *src = 0;
    IplImage *dst = 0;
    src = cvLoadImage("test.bmp"); //create image matrixes..
    dst = cvLoadImage("test.bmp"); //
    CvMat *filter;
    double kernel[KERNELLENGTH * KERNELLENGTH]; //create an appropriate kernel
    int r = KERNELLENGTH / 2; //calculate the radius
    double value = 1 / (PI * KERNELLENGTH * KERNELLENGTH / (4 * r)); //calculate the defocus blur value
    cout << "Kernel:" << "\n";
    for (int x = 0; x < KERNELLENGTH; x++) //calculate kernel (seems to work right!)
    {
        for (int y = 0; y < KERNELLENGTH; y++) {
            if (sqrt((x - KERNELLENGTH / 2) * (x - KERNELLENGTH / 2) + (y
                    - KERNELLENGTH / 2) * (y - KERNELLENGTH / 2)) <= r) {
                kernel[y * 4 + x] = value; //Wert zuweisen
                cout << value << "\t";
            } else
                cout << 0 << "\t";
        }
        cout << "\n";
    }

    filter = cvCreateMatHeader(KERNELLENGTH, KERNELLENGTH, CV_32FC1);//create the filter
    cvSetData(filter, kernel, KERNELLENGTH * sizeof(kernel[0]));//link kernel and filter
    cvFilter2D(src, //convolve filter and src, save to dst
            dst, filter, cvPoint(-1, -1));

    cvSaveImage("test_out.bmp", dst); //save dst on disk

    cvReleaseImage(&src);
    cvReleaseImage(&dst);
    return 0;
}

我真的很感激这方面的帮助,谢谢!

1 个答案:

答案 0 :(得分:0)

似乎问题出在#define KERNELLENGTH 3,因为你得到KERNELLENGTH / 2 == 1并且内核是3比3的东西,我不称之为正确的散焦盘。

你是否用例如#define KERNELLENGTH 10