#include <opencv2corecore.hpp>
#include <opencv2highguihighgui.hpp>
#include <opencv2imgprocimgproc.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边缘检测制作代码。但是错误块打开图像和 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:opencvbuildincludeopencv2coremat.hpp, line 538
所以我无法进入下一步。
示例中存在一些编码错误。一个是您在语句for loop
中超出了 Mat 数据的界限 sj + j - verticleimagebound / 2, si + i - horizantalimagebound/2
.这应该是sj + j - verticleimagebound, si + i - horizantalimagebound
.
另一种是,您正在从不存在数据的grayimage
访问像素。您应该将image
的输入数据克隆到grayimage
中。