sobel算法原理
1算子模板
2图片卷积
3阈值判决
sobel算子模板
竖直方向算子
[121000−1−2−1]
\left[
\begin{matrix}
1 & 2 & 1 \\
0& 0& 0 \\
-1& -2 & -1
\end{matrix}
\right]
⎣⎡10−120−210−1⎦⎤
水平方向算子
[10−120−210−1]
\left[
\begin{matrix}
1 & 0& -1 \\
2& 0& -2 \\
1 & 0 & -1
\end{matrix}
\right]
⎣⎡121000−1−2−1⎦⎤
图片卷积
假设有一张图片有[1,2,3,4]4个点,每个点表明一个像素。当前计算模板是[a,b,c,d]那么卷积后a1+b2+c3+d4=dst
假设c为竖直方向上的梯度,c为竖直方向算子与图像像素点的卷积和,同理d为水平上的算子
sqrt(cc+dd)为幅值如果大于th判决门线则为边缘,小于就是非边缘。


import cv2
import numpy as np
import random
import math
img = cv2.imread('image0.jpg',1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
cv2.imshow('src',img)
# sobel 1 算子模版 2 图片卷积 3 阈值判决
# [1 2 1 [ 1 0 -1
# 0 0 0 2 0 -2
# -1 -2 -1 ] 1 0 -1 ]
# [1 2 3 4] [a b c d] a*1+b*2+c*3+d*4 = dst
# sqrt(a*a+b*b) = f>th
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
dst = np.zeros((height,width,1),np.uint8)
for i in range(0,height-2):
for j in range(0,width-2):
gy = gray[i,j]*1+gray[i,j+1]*2+gray[i,j+2]*1-gray[i+2,j]*1-gray[i+2,j+1]*2-gray[i+2,j+2]*1
gx = gray[i,j]+gray[i+1,j]*2+gray[i+2,j]-gray[i,j+2]-gray[i+1,j+2]*2-gray[i+2,j+2]
grad = math.sqrt(gx*gx+gy*gy)
if grad>50:
dst[i,j] = 255
else:
dst[i,j] = 0
cv2.imshow('dst',dst)
cv2.waitKey(0)
17万+

被折叠的 条评论
为什么被折叠?



