sobel边缘检测错误(opencv错误:断言失败(dims< = 2&& data&&&(unsigned)i0)

时间:2016-01-27 04:05:29

标签: c++ opencv sobel

#include <opencv2\core\core.hpp>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\imgproc\imgproc.hpp>
#include <iostream>
#include <cmath>
using namespace cv;
using namespace std;

int main()
{
    Mat image = imread("lena.jpg", CV_LOAD_IMAGE_GRAYSCALE);

    if (!image.data)
    {
        cout << "we can not open an image!!" << endl;
        return -1;
    }

    const int sobel_width = 3;
    const int sobel_height = 3;

    int sobel_y[sobel_width][sobel_height] = {
        {-1,-2,-1},
        {0, 0, 0},
        {1, 2, 1}
    };

    int sobel_x[sobel_width][sobel_height] = {
        { -1, 0, 1 },
        { -2, 0, 2 },
        { -1, 0, 1 }
    };
    Mat grayimage(image.size(), CV_8UC1);

    Mat final(image.size(), CV_8UC1);

    int SUM;
    int verticleimagebound = (sobel_height - 1) / 2;
    int horizantalimagebound = (sobel_width - 1) / 2;

    for (int j = 0+verticleimagebound; j < image.rows - verticleimagebound; j++)
    {
        for (int i = 0+horizantalimagebound; i < image.cols - horizantalimagebound; i++)
        {
            int sum_x=0, sum_y = 0;
            for (int sj = 0; sj < 3; sj++)
            {
                for (int si = 0; si < 3; si++)
                {
                    int pixel1 = grayimage.at<uchar>(sj + j - verticleimagebound / 2, si + i - horizantalimagebound/2)*sobel_x[sj][si];
                    sum_x += pixel1;
                    int pixel2 = grayimage.at<uchar>(sj + j - verticleimagebound / 2, si + i - horizantalimagebound/2)*sobel_y[sj][si];
                    sum_y += pixel2;
                }
            }
            SUM = abs((int)sum_x) + abs((int)sum_y);
            if (SUM > 255)
            {
                SUM = 255;
            }
            else if (SUM < 0)
            {
                SUM = 0;
            }
            final.at<uchar>(j, i) = 255 - (uchar)(SUM);
        }
    }

    namedWindow("orginal", 1);
    imshow("orginal", image);

    namedWindow("sobel", 1);
    imshow("sobel", final);

    waitKey(0);
    return 0;

}

现在我正在尝试为sobel边缘检测制作代码。但错误阻止打开图像和索贝尔边缘图像。当我调试我的代码时,窗口会这样说:

OpenCv Error: Assertion failed (
    dims <= 2 
    && data 
    && (unsigned)i0 < (unsigned)size.p[0] 
    && (unsigned)(i1*DataType<_Tp>::channedls) < (unsigned)(size.p[1]*channels()) 
    && ((((sizeof(size_t)<<28)|0x8442211)>>((DataType<_Tp>::depth) & ((1 << 3)-1))*4) & 15) == elemmSize1()) 
  in cv:: Mat::at, file c:\opencv\build\include\opencv2\core\mat.hpp, line 538

所以我无法进入下一步。

1 个答案:

答案 0 :(得分:1)

您的样本中存在一些编码错误。 一个是您在for loop中使用该语句超出了Mat数据的范围 sj + j - verticleimagebound / 2, si + i - horizantalimagebound/2。这应该是sj + j - verticleimagebound, si + i - horizantalimagebound

另外,您正在访问grayimage中没有数据的像素。您应该将image的输入数据克隆到grayimage