OpenCV - Sobel算子源码实现边缘检测(Python实现)

Soble算子边缘检测就用算子模板卷积求像素点的梯度,如果梯度大于设定值则认为是边缘点,否则不是边缘点。

import cv2
import numpy as np
import random
import math
img = cv2.imread("img.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]
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):
        #计算x y方向的梯度
        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]*1+gray[i+1,j]*2+gray[i+2,j]*1-gray[i,j+2]*1-gray[i+1,j+2]*2-gray[i+2,j+2]*1
        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)

OpenCV - Sobel算子源码实现边缘检测(Python实现)_第1张图片

你可能感兴趣的:(【OpenCV】,OpenCV)