一、

1.调用api实现边缘检测:

1)读入灰度图像

2)使用高斯滤波去除图像中的一些噪声点,平滑图像

3)使用canny边缘检测算法

2. cv2.GaussianBlur(img,size,sigmax),高斯滤波,去除图像噪声点,使图像整体平滑

       img,原图像

       size,滤波窗口/高斯矩阵尺寸(通常为奇数),越大越模糊

       sigmax,高斯矩阵标准差,越大越模糊

3.cv2.Canny(img, threshold1, threshold2[, edges[, apertureSize[, L2gradient ]]])

Img,原图像

Threshold1,最小阈值,用于处理不连续的小边缘

Threshold2,最大阈值,用于识别较明显的连续大边缘

4.sobel算子:

1)横向互相关/卷积模版:opencv学习19——边缘检测-LMLPHP ;纵向互相关/卷积模版opencv学习19——边缘检测-LMLPHP

计算得到横向梯度与纵向梯度

2)计算梯度浮值/像素值,等于横向梯度平方加纵向梯度平方的和后再开方。

3)将梯度浮值与阈值比较,判断是否为边缘

二、

1.api

import cv2

th1 = 50
th2 = 150

grayImg = cv2.imread('image01.jpg',1)

imgG = cv2.GaussianBlur(grayImg, (3, 3), 0)

dstImg = cv2.Canny(grayImg, th1, th2)

cv2.imshow('', dstImg)
cv2.waitKey(0)
cv2.destroyAllWindows()

2.sobel

# sobel 算子
# [ 1  2  1             [ 1  0 -1
#  0  0  0               2  0 -2
# -1 -2 -1 ]             1  0 -1 ]
# sqrt(a*a+b*b) = f >th

import cv2
import numpy as np
import math

threshold = 100

grayImg = cv2.imread('image01.jpg', 0)
imgHeight, imgWidth = grayImg.shape

dstImg = np.zeros((imgHeight, imgWidth, 1), np.uint8)

for i in range(1, imgHeight - 1):
    for j in range(1, imgWidth - 1):
        gy = grayImg[i - 1, j - 1] * 1 + grayImg[i - 1, j] * 2 + grayImg[i - 1, j + 1] * 1 - grayImg[i + 1, j - 1] * 1 - \
             grayImg[i + 1, j] * 2 - grayImg[i + 1, j + 1]
        gx = grayImg[i - 1, j - 1] * 1 + grayImg[i, j - 1] * 2 + grayImg[i + 1, j - 1] * 1 - grayImg[i - 1, j + 1] * 1 - \
             grayImg[i, j + 1] * 2 - grayImg[i + 1, j + 1]
        grad = math.sqrt(gx * gx + gy * gy)
        if grad > threshold:
            dstImg[i, j] = 255
        else:
            dstImg[i, j] = 0

cv2.imshow('', dstImg)
cv2.waitKey(0)
cv2.destroyAllWindows()

 

10-07 11:28