Openmp c ++ sobel边缘检测

时间:2014-01-06 23:49:29

标签: c++ openmp edge-detection

我对最终图片有问题,它是扭曲的,我不知道为什么。只有当我在Visual Studio中打开openmp选项时才会这样。如果它为一个线程工作没有问题,边缘清晰。代码就在下面。

#include "stdafx.h"
#include<iostream>
#include<omp.h>
#include<cmath>
#include<opencv2/imgproc/imgproc.hpp>
#include<opencv2/highgui/highgui.hpp>
using namespace std;
using namespace cv;

int xGradient(Mat image, int x, int y)
{
return image.at<uchar>(y-1, x-1) +
            2*image.at<uchar>(y, x-1) +
             image.at<uchar>(y+1, x-1) -
              image.at<uchar>(y-1, x+1) -
               2*image.at<uchar>(y, x+1) -
                image.at<uchar>(y+1, x+1);
}
int yGradient(Mat image, int x, int y)
{
    return image.at<uchar>(y-1, x-1) +
            2*image.at<uchar>(y-1, x) +
             image.at<uchar>(y-1, x+1) -
              image.at<uchar>(y+1, x-1) -
               2*image.at<uchar>(y+1, x) -
                image.at<uchar>(y+1, x+1);
}
int main()

 {

  Mat src, grey, dst;
 double start, end;
     start = omp_get_wtime();
  int gx, gy, sum;
src= imread("E:/image.jpg");  
cvtColor(src,grey,CV_BGR2GRAY);
  dst = grey.clone();
  if( !grey.data )
  { return -1; }
 #pragma omp parallel for  
  for(int y = 0; y < grey.rows; y++)
        for(int x = 0; x < grey.cols; x++)
            dst.at<uchar>(y,x) = 0;  
 #pragma omp parallel for
   for(int y = 1; y < grey.rows - 1; y++){
        for(int x = 1; x < grey.cols - 1; x++){
            gx = xGradient(grey, x, y);
            gy = yGradient(grey, x, y);
            sum = abs(gx) + abs(gy);
            sum = sum > 255 ? 255:sum;
            sum = sum < 0 ? 0 : sum;
            dst.at<uchar>(y,x) = sum;

                }
    }
    namedWindow("sobel");
    imshow("sobel", dst);
    namedWindow("grayscale");
    imshow("grayscale", grey);
    namedWindow("Original");
    imshow("Original", src);
    end = omp_get_wtime();
    cout<<"time is: "<<(end-start)<< " seconds" <<endl;
waitKey();
    return 0;
}

感谢您提供任何帮助和解答

2 个答案:

答案 0 :(得分:0)

gxgysum中存在竞争条件。它们都是共享的,应该是私有的。只需在并行循环中使用它们时定义它们就可以解决问题。喜欢这个

   #pragma omp parallel for
   for(int y = 1; y < grey.rows - 1; y++){
        for(int x = 1; x < grey.cols - 1; x++){
            int gx = xGradient(grey, x, y);
            int gy = yGradient(grey, x, y);
            int sum = abs(gx) + abs(gy);
            sum = sum > 255 ? 255:sum;
            sum = sum < 0 ? 0 : sum;
            dst.at<uchar>(y,x) = sum;

答案 1 :(得分:0)

  

我希望这可以帮助你:)

 #pragma omp parallel for private (gx, gy, sum) //num_threads (2)
    for(int y = 1; y < grey.rows - 1; y++){
        for(int x = 1; x < grey.cols - 1; x++){     
            gx = xGradient(grey, x, y);
            gy = yGradient(grey, x, y);
            sum = abs(gx) + abs(gy);
            sum = sum > 255 ? 255:sum;
            sum = sum < 0 ? 0 : sum;
            dst.at<uchar>(y,x) = sum;
        }
    }