opencv边缘检测运用sobel算子源代码方法

    科技2024-04-03  92

    opencv边缘检测运用sobel算子源代码方法

    import cv2 import numpy as np import random import math img0 = cv2.imread(r"C:\Users\lenovo\Desktop\python\python_vision\image.jpg",1) imgInfo = img0.shape height = imgInfo[0] weight = imgInfo[1] # 转换灰度图像 2.高斯滤波 gray = cv2.cvtColor(img0,cv2.COLOR_RGB2GRAY) imgG = cv2.GaussianBlur(gray,(3,3),0) dst = np.zeros((height,weight,1),np.uint8) for i in range(0,height-2): for j in range(0,weight-2): gy = imgG[i,j]*1+imgG[i,j+1]*2+imgG[i,j+2]*1-imgG[i+2,j]*1-imgG[i+2,j+1]*2-imgG[i+2,j+2]*1 gx = imgG[i,j]*1-imgG[i+2,j]*1+imgG[i+1,j]*2-imgG[i+1,j+2]*2+imgG[i+2,j]*1-imgG[i+2,j+2]*1 grad = math.sqrt(gx*gx+gy*gy) if grad>20: dst[i,j] = 0 else: dst[i,j] = 255 cv2.imshow("dst",dst) cv2.waitKey()

    效果图片: 代码解释:

    for i in range(0,height-2): for j in range(0,weight-2): gy = imgG[i,j]*1+imgG[i,j+1]*2+imgG[i,j+2]*1-imgG[i+2,j]*1-imgG[i+2,j+1]*2-imgG[i+2,j+2]*1 gx = imgG[i,j]*1-imgG[i+2,j]*1+imgG[i+1,j]*2-imgG[i+1,j+2]*2+imgG[i+2,j]*1-imgG[i+2,j+2]*1 grad = math.sqrt(gx*gx+gy*gy) if grad>20: dst[i,j] = 0 else: dst[i,j] = 255

    分别让3X3的像素乘以sobel算子,然后求gx+gy平方和的根值,判断其大于或者小于某一个值。 边缘检测有:Laplace算子,sobel算子和canny算子等等

    Processed: 0.015, SQL: 8