错误的渐变矢量场OpenCV C ++

时间:2015-11-24 16:42:54

标签: c++ opencv gradient

我尝试在OpenCV(C ++)中显示图像的渐变矢量场。

我使用了来自Plotting a Gradient Vector Field in OpenCV的代码:

cv::Mat img(cv::imread("C:/gradient2.png",1));

cv::Mat smoothedPlane = cv::Mat::zeros(img.rows,img.cols,CV_8UC1);
cv::Mat gradientField = cv::Mat::zeros(img.rows,img.cols,CV_32FC2);

cv::Mat GradX, GradY;
//cv::Mat AbsGradX, AbsGradY;

int ddepth = CV_16S;
int scale = 1;
int delta = 0;    
auto size = 40;

GaussianBlur(img,smoothedPlane,cv::Size(51, 51),img.rows*img.cols*0.5);

erode(smoothedPlane, smoothedPlane, cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(size+1,size+1)));
dilate(smoothedPlane, smoothedPlane, cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(size, size)));

dilate(smoothedPlane, smoothedPlane, cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(size, size)));
erode(smoothedPlane, smoothedPlane, cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(size, size)));

Scharr( smoothedPlane, GradX, ddepth, 1, 0, scale);
Scharr( smoothedPlane, GradY, ddepth, 0, 1, scale);

//convertScaleAbs( GradX, AbsGradX );
//convertScaleAbs( GradY, AbsGradY );

for (int i = 0 ; i < GradX.rows ; i ++)
{
    for (int j = 0 ; j < GradX.cols ; j ++)
    {
        cv::Scalar xval = GradX.at<float>(i,j);
        cv::Scalar yval = GradY.at<float>(i,j);
        gradientField.at<cv::Point2f>(i,j) = cv::Point2f(xval.val[0],yval.val[0]);
    }
}

auto resolution = 30;

for (int i = 0 ; i < img.rows ; i += resolution)
{
    for (int j = 0 ; j < img.cols ; j+= resolution)
    {
        cv::Point2f p(j,i);
        cv::Point2f p2(gradientField.at<cv::Point2f>(p)+p);
        cv::arrowedLine(img,p,p2,cv::Scalar(0,0,255),1.5,8,0,0.1);
    }
}

cv::imshow("gradient", img);
cv::waitKey(0);

如果我通过此访问复制渐变值:

        cv::Scalar xval = GradX.at<float>(i,j);
        cv::Scalar yval = GradY.at<float>(i,j);

输出的结果类似于result with float access

如果我通过此访问复制渐变值:

        cv::Scalar xval = GradX.at<short>(i,j);
        cv::Scalar yval = GradY.at<short>(i,j);

输出的结果类似于result with short access

正确的结果应该显示来自暗盘的外边框的箭头线指向磁盘的外部。提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我想我找到了解决方案,我将输入图像转换为灰度:

cv::cvtColor(img, img, CV_BGR2GRAY);

并保持

        cv::Scalar xval = GradX.at<short>(i,j);
        cv::Scalar yval = GradY.at<short>(i,j);

结果如下:Good gradient vector field