开发者

creating 3x3 sobel operator in opencv2 C++

开发者 https://www.devze.com 2023-04-13 03:59 出处:网络
Im trying to create my own sobel edge detect开发者_JS百科ion based off of the gx and gy matrices on three channels i have in my code below.

Im trying to create my own sobel edge detect开发者_JS百科ion based off of the gx and gy matrices on three channels i have in my code below.

[[0,1,2], [-1,0,1], [-2,-1,0]] and

[-2,-1,0],
 [-1,0,1],
 [0,1,2]]

I edited the variables j and i in my code further down but it is not working, how can i create a sobel edge detection on those three channels

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>

void salt(cv::Mat &image, int n) {

int i,j;
for (int k=0; k<n; k++) {

    // rand() is the MFC random number generator
    i= rand()%image.cols;
    j= rand()%image.rows;


    if (image.channels() == 1) { // gray-level image

        image.at<uchar>(j,i)= 255; 

    } else if (image.channels() == 3) { // color image

        image.at<cv::Vec3b>(j,i)[0]= 255; 
        image.at<cv::Vec3b>(j-1,i-1)[1]= 255; 
        image.at<cv::Vec3b>(j,i-1)[2]= 255; 
    }
}
}

int main()
{
srand(cv::getTickCount()); // init random number generator

cv::Mat image= cv::imread("space.jpg",0);

salt(image,3000);

cv::namedWindow("Image");
cv::imshow("Image",image);

cv::imwrite("salted.bmp",image);

cv::waitKey(5000);

return 0;
}


I'm a little confused by the question, because the question relates to sobel filters, but you provided a function that adds noise to an image.

To start with, here is the Sobel function, which will call the classic sobel functions (that will calculate dx and dy gradients).

Secondly, there is the more generic filter2D which will let you apply an arbitrary kernel (like the one you created in the question).

Lastly, if you want to apply a different kernel in each channel or band, you can do as the filter2D documentation implies, and call split on an image, and then call filter2D on each channel, and then combine the values into a single band image using the matrix operators.

The most complicated thing I think you could be asking is how to find the locations of that salt you added to the image, and the answer would be to make a kernel for each band like so:

band 0:

[[ 0, 0, 0],
 [ 0, 1, 0],
 [ 0, 0, 0]]

band 1:

[[ 1, 0, 0],
 [ 0, 0, 0],
 [ 0, 0, 0]]

band 2:

[[ 0, 1, 0],
 [ 0, 0, 0],
 [ 0, 0, 0]]

Be sure to put the anchor in the center of the kernel (1,1).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号