gpt4 book ai didi

c++ - OpenCV中手动实现Sobel算子

转载 作者:太空宇宙 更新时间:2023-11-03 22:47:44 31 4
gpt4 key购买 nike

我正在尝试通过遍历图像并对周围像素应用 mask 来应用 sobel 运算符。

现在,我正在尝试应用蒙版的垂直部分,即:

-1 0 1
-2 0 2
-1 0 1

在我的实现中,我按如下方式遍历行和列:

for (int i = 1; i < image.rows-1; i++){
for (int j = 1; j < image.cols-1; j++){
int pixel1 = image.at<Vec3b>(i-1,j-1)[0] * -1;
int pixel2 = image.at<Vec3b>(i,j-1)[0] * 0;
int pixel3 = image.at<Vec3b>(i+1,j-1)[0] * 1;

int pixel4 = image.at<Vec3b>(i-1,j)[0] * -2;
int pixel5 = image.at<Vec3b>(i,j)[0] * 0;
int pixel6 = image.at<Vec3b>(i+1,j)[0] * 2;

int pixel7 = image.at<Vec3b>(i-1,j+1)[0] * -1;
int pixel8 = image.at<Vec3b>(i,j+1)[0] * 0;
int pixel9 = image.at<Vec3b>(i+1,j+1)[0] * 1;

int sum = pixel1 + pixel2 + pixel3 + pixel4 + pixel5 + pixel6 + pixel7 + pixel8 + pixel9;
verticalSobel.at<Vec3b>(i,j)[0] = sum;
verticalSobel.at<Vec3b>(i,j)[1] = sum;
verticalSobel.at<Vec3b>(i,j)[2] = sum;
}
}

像素标记为:

1 2 3
4 5 6
7 8 9

但是,生成的图像与其应有的样子相去甚远。

作为引用,生成的图像是 enter image description here

它看起来应该类似于: enter image description here

我使用的指南是:https://www.tutorialspoint.com/dip/sobel_operator.htm

我不确定我是否只是错误地实现了运算符,或者只是错误地遍历了图像。

如有任何帮助,我们将不胜感激。谢谢!

最佳答案

您似乎遇到了总和为负的问题。取 sum 的绝对值,并将其限制为 255(或者代替绝对值,将其限制为 0 - 这取决于您想要实现的目标。“完整”sobel 运算符通常使用 2d 距离公式,因此仅水平/垂直变体应使用绝对值)

关于c++ - OpenCV中手动实现Sobel算子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44809271/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com