图像处理之canny边缘检测(非极大值抑制和高低阈值)

这篇具有很好参考价值的文章主要介绍了图像处理之canny边缘检测(非极大值抑制和高低阈值)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Canny 边缘检测方法

Canny算子是John F.Canny 大佬在1986年在其发表的论文 《Canny J. A computational approach to edge detection [J]. IEEE Transactions on Pattern Analysis and Machine Intelligence, 1986 (6): 679-698.》提出来的。

检测目标:

  • 低错误率。所有边缘都应该被找到,并且应该没有伪响应。也就是检测到的边缘必须尽可能时真实的边缘。
  • 边缘点应被很好地定位。已定位边缘必须尽可能接近真实边缘。也就是由检测器标记为边缘的点和真实边缘的中心之间的距离应该最小。
  • 单一的边缘点响应。这意味着在仅存一个单一边缘点的位置,检测器不应指出多个边缘像素。

Canny算法步骤

①高斯模糊 - GaussianBlur
②灰度转换 - cvtColor
③计算梯度 – Sobel/Scharr
④非最大信号抑制
⑤高低阈值输出二值图像——高低阈值比值为2:1或3:1最佳

1.灰度转换

点击图像处理之图像灰度化查看

2.高斯模糊

点击图像处理之高斯滤波查看

3.计算梯度

点击图像处理之梯度及边缘检测算子查看

4.非极大抑制

非极大值抑制是进行边缘检测的一个重要步骤,通俗意义上是指寻找像素点局部最大值。沿着梯度方向,比较它前面和后面的梯度值,如果它不是局部最大值,则去除。
图像处理之canny边缘检测(非极大值抑制和高低阈值),图像处理,图像处理,人工智能
在John Canny提出的Canny算子的论文中,非最大值抑制就只是在 0 ∘ 、 9 0 ∘ 、 4 5 ∘ 、 13 5 ∘ 0^\circ、90^\circ、45^\circ、135^\circ 09045135四个梯度方向上进行的,每个像素点梯度方向按照相近程度用这四个方向来代替。这四种情况也代表着四种不同的梯度,即
G y > G x G_y>G_x Gy>Gx,且两者同号。
G y > G x G_y>G_x Gy>Gx,且两者异号。
G y < G x G_y<G_x Gy<Gx,且两者同号。
G y < G x G_y<G_x Gy<Gx,且两者异号。
如上图所示,根据X方向和Y方向梯度的大小可以判断A点是靠近X轴还是Y轴,通过A1和A2的像素值则可计算A点的亚像素值,B点同理,不再赘述。上面两图为靠近Y轴的梯度大,下面两图为靠近X轴的像素大。
由于A、B两点的位置是通过梯度来确定的,那么A、B两点的梯度值也可以根据Q点的梯度计算,因此假设Q点在四个方向上的梯度分别为 G 1 G_1 G1 G 2 G_2 G2 G 3 G_3 G3 G 4 G_4 G4
G y > G x G_y>G_x Gy>Gx时, w = G x G y , G 1 = ( i − 1 , j ) , G 2 = ( i + 1 , j ) w=\frac{G_x}{G_y},G_1=(i-1,j),G_2=(i+1,j) w=GyGx,G1=(i1,j),G2=(i+1,j)
两者同号时: G 3 = ( i − 1 , j − 1 ) , G 4 = ( i + 1 , j + 1 ) G_3=(i-1,j-1),G_4=(i+1,j+1) G3=(i1,j1),G4=(i+1,j+1)
两者异号时: G 3 = ( i − 1 , j + 1 ) , G 4 = ( i + 1 , j − 1 ) G_3=(i-1,j+1),G_4=(i+1,j-1) G3=(i1,j+1),G4=(i+1,j1)
G y < G x G_y<G_x Gy<Gx时, w = G y G x , G 1 = ( i , j − 1 ) , G 2 = ( i , j + 1 ) w=\frac{G_y}{G_x},G_1=(i,j-1),G_2=(i,j+1) w=GxGy,G1=(i,j1),G2=(i,j+1)
两者同号时: G 3 = ( i + 1 , j − 1 ) , G 4 = ( i + 1 , j − 1 ) G_3=(i+1,j-1),G_4=(i+1,j-1) G3=(i+1,j1),G4=(i+1,j1)
两者异号时: G 3 = ( i − 1 , j − 1 ) , G 4 = ( i + 1 , j + 1 ) G_3=(i-1,j-1),G_4=(i+1,j+1) G3=(i1,j1),G4=(i+1,j+1)
如此便可以计算出两个相邻亚像素点的梯度值
g A = w ∗ G 1 + ( 1 − w ) ∗ G 3 g B = w ∗ G 2 + ( 1 − w ) ∗ G 4 g_A=w*G_1+(1-w)*G_3\\ g_B=w*G_2+(1-w)*G_4 gA=wG1+(1w)G3gB=wG2+(1w)G4
比较三者的像素值,如果Q点像素值大于其余两者,则保留Q点作为边缘上的点,否则认为Q点为冗余点。
python代码:

ef NMS(gradients, direction):
    """ Non-maxima suppression

    Args:
        gradients: the gradients of each pixel
        direction: the direction of the gradients of each pixel

    Returns:
        the output image
    """
    W, H = gradients.shape
    nms = np.copy(gradients[1:-1, 1:-1])

    for i in range(1, W - 1):
        for j in range(1, H - 1):
            theta = direction[i, j]
            weight = np.tan(theta)
            if theta > np.pi / 4:
                d1 = [0, 1]
                d2 = [1, 1]
                weight = 1 / weight
            elif theta >= 0:
                d1 = [1, 0]
                d2 = [1, 1]
            elif theta >= - np.pi / 4:
                d1 = [1, 0]
                d2 = [1, -1]
                weight *= -1
            else:
                d1 = [0, -1]
                d2 = [1, -1]
                weight = -1 / weight

            g1 = gradients[i + d1[0], j + d1[1]]
            g2 = gradients[i + d2[0], j + d2[1]]
            g3 = gradients[i - d1[0], j - d1[1]]
            g4 = gradients[i - d2[0], j - d2[1]]

            grade_count1 = g1 * weight + g2 * (1 - weight)
            grade_count2 = g3 * weight + g4 * (1 - weight)

            if grade_count1 > gradients[i, j] or grade_count2 > gradients[i, j]:
                nms[i - 1, j - 1] = 0

    return nms

5.双阈值跟踪边界

设置两个阈值,minVal和maxVal。梯度大于maxVal的任何边缘是真边缘,而minVal以下的边缘是非边缘。位于这两个阈值之间的边缘会基于其连通性而分类为边缘或非边缘,如果它们连接到“可靠边缘”像素,则它们被视为边缘的一部分;否则,不是边缘。
代码如下:

def double_threshold(nms, threshold1, threshold2):
    """ Double Threshold
    Use two thresholds to compute the edge.

    Args:
        nms: the input image
        threshold1: the low threshold
        threshold2: the high threshold

    Returns:
        The binary image.
    """

    visited = np.zeros_like(nms)
    output_image = nms.copy()
    W, H = output_image.shape

    def dfs(i, j):
        if i >= W or i < 0 or j >= H or j < 0 or visited[i, j] == 1:
            return
        visited[i, j] = 1
        if output_image[i, j] > threshold1:
            output_image[i, j] = 255
            dfs(i-1, j-1)
            dfs(i-1, j)
            dfs(i-1, j+1)
            dfs(i, j-1)
            dfs(i, j+1)
            dfs(i+1, j-1)
            dfs(i+1, j)
            dfs(i+1, j+1)
        else:
            output_image[i, j] = 0


    for w in range(W):
        for h in range(H):
            if visited[w, h] == 1:
                continue
            if output_image[w, h] >= threshold2:
                dfs(w, h)
            elif output_image[w, h] <= threshold1:
                output_image[w, h] = 0
                visited[w, h] = 1

    for w in range(W):
        for h in range(H):
            if visited[w, h] == 0:
                output_image[w, h] = 0
    return output_image

整体代码如下:

# -*- coding: utf-8 -*-
import numpy as np
import cv2
import imgShow as iS

def smooth(image, sigma = 1.4, length = 5):
    """ Smooth the image
    Compute a gaussian filter with sigma = sigma and kernal_length = length.
    Each element in the kernal can be computed as below:
        G[i, j] = (1/(2*pi*sigma**2))*exp(-((i-k-1)**2 + (j-k-1)**2)/2*sigma**2)
    Then, use the gaussian filter to smooth the input image.

    Args:
        image: array of grey image
        sigma: the sigma of gaussian filter, default to be 1.4
        length: the kernal length, default to be 5

    Returns:
        the smoothed image
    """
    # Compute gaussian filter
    k = length // 2
    gaussian = np.zeros([length, length])
    for i in range(length):
        for j in range(length):
            gaussian[i, j] = np.exp(-((i-k) ** 2 + (j-k) ** 2) / (2 * sigma ** 2))
    gaussian /= 2 * np.pi * sigma ** 2
    # Batch Normalization
    gaussian = gaussian / np.sum(gaussian)

    # Use Gaussian Filter
    W, H = image.shape
    new_image = np.zeros([W - k * 2, H - k * 2])

    for i in range(W - 2 * k):
        for j in range(H - 2 * k):
            new_image[i, j] = np.sum(image[i:i+length, j:j+length] * gaussian)

    new_image = np.uint8(new_image)

    return new_image


def get_gradient_and_direction(image):
    """ Compute gradients and its direction
    Use Sobel filter to compute gradients and direction.
         -1 0 1        -1 -2 -1
    Gx = -2 0 2   Gy =  0  0  0
         -1 0 1         1  2  1

    Args:
        image: array of grey image

    Returns:
        gradients: the gradients of each pixel
        direction: the direction of the gradients of each pixel
    """
    Gx = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
    Gy = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]])

    W, H = image.shape
    gradients = np.zeros([W - 2, H - 2])
    direction = np.zeros([W - 2, H - 2])

    for i in range(W - 2):
        for j in range(H - 2):
            dx = np.sum(image[i:i+3, j:j+3] * Gx)
            dy = np.sum(image[i:i+3, j:j+3] * Gy)
            gradients[i, j] = np.sqrt(dx ** 2 + dy ** 2)
            if dx == 0:
                direction[i, j] = np.pi / 2
            else:
                direction[i, j] = np.arctan(dy / dx)

    gradients = np.uint8(gradients)

    return gradients, direction


def NMS(gradients, direction):
    """ Non-maxima suppression

    Args:
        gradients: the gradients of each pixel
        direction: the direction of the gradients of each pixel

    Returns:
        the output image
    """
    W, H = gradients.shape
    nms = np.copy(gradients[1:-1, 1:-1])

    for i in range(1, W - 1):
        for j in range(1, H - 1):
            theta = direction[i, j]
            weight = np.tan(theta)
            if theta > np.pi / 4:
                d1 = [0, 1]
                d2 = [1, 1]
                weight = 1 / weight
            elif theta >= 0:
                d1 = [1, 0]
                d2 = [1, 1]
            elif theta >= - np.pi / 4:
                d1 = [1, 0]
                d2 = [1, -1]
                weight *= -1
            else:
                d1 = [0, -1]
                d2 = [1, -1]
                weight = -1 / weight

            g1 = gradients[i + d1[0], j + d1[1]]
            g2 = gradients[i + d2[0], j + d2[1]]
            g3 = gradients[i - d1[0], j - d1[1]]
            g4 = gradients[i - d2[0], j - d2[1]]

            grade_count1 = g1 * weight + g2 * (1 - weight)
            grade_count2 = g3 * weight + g4 * (1 - weight)

            if grade_count1 > gradients[i, j] or grade_count2 > gradients[i, j]:
                nms[i - 1, j - 1] = 0

    return nms


def double_threshold(nms, threshold1, threshold2):
    """ Double Threshold
    Use two thresholds to compute the edge.

    Args:
        nms: the input image
        threshold1: the low threshold
        threshold2: the high threshold

    Returns:
        The binary image.
    """

    visited = np.zeros_like(nms)
    output_image = nms.copy()
    W, H = output_image.shape

    def dfs(i, j):
        if i >= W or i < 0 or j >= H or j < 0 or visited[i, j] == 1:
            return
        visited[i, j] = 1
        if output_image[i, j] > threshold1:
            output_image[i, j] = 255
            dfs(i-1, j-1)
            dfs(i-1, j)
            dfs(i-1, j+1)
            dfs(i, j-1)
            dfs(i, j+1)
            dfs(i+1, j-1)
            dfs(i+1, j)
            dfs(i+1, j+1)
        else:
            output_image[i, j] = 0


    for w in range(W):
        for h in range(H):
            if visited[w, h] == 1:
                continue
            if output_image[w, h] >= threshold2:
                dfs(w, h)
            elif output_image[w, h] <= threshold1:
                output_image[w, h] = 0
                visited[w, h] = 1

    for w in range(W):
        for h in range(H):
            if visited[w, h] == 0:
                output_image[w, h] = 0

    return output_image


if __name__ == "__main__":
    # code to read image
    img=cv2.imread('./originImg/Lena.tif')
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    smoothed_image = smooth(img)
    gradients, direction = get_gradient_and_direction(smoothed_image)
    nms = NMS(gradients, direction)
    output_image = double_threshold(nms, 40, 100)
    imageList = []
    origin_img = [img, 'origin_img']
    imageList.append(origin_img)
    # smoothed= [smoothed_image, ' smoothed_image']
    # imageList.append(smoothed)
    gradient = [gradients, 'gradients']
    imageList.append(gradient)
    nms = [nms, 'nms']
    imageList.append(nms)
    output_images = [output_image, 'output_image']
    imageList.append(output_images)
    iS.showMultipleimages(imageList, 25, 25, './ProcessedImg/canny.jpg')

检测结果:
图像处理之canny边缘检测(非极大值抑制和高低阈值),图像处理,图像处理,人工智能文章来源地址https://www.toymoban.com/news/detail-599850.html

到了这里,关于图像处理之canny边缘检测(非极大值抑制和高低阈值)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 数字图像处理【11】OpenCV-Canny边缘提取到FindContours轮廓发现

    本章主要介绍图像处理中一个比较基础的操作:Canny边缘发现、轮廓发现 和 绘制轮廓。概念不难,主要是结合OpenCV 4.5+的API相关操作,为往下 \\\"基于距离变换的分水岭图像分割\\\" 做知识储备。 在讲述轮廓之前,要花点时间学学边缘检测提取的一个著名算法——Canny边缘提取算法

    2024年02月16日
    浏览(29)
  • Canny边缘检测方法中的非极大抑制

    什么是非极大抑制 在目标检测中,通常会使用各种各样的方法来让计算机找到目标的所在位置,然而,计算机的输出往往并不是单一的,也就是说,一个目标可能会输出多个结果(如下图所示),这些结果有好有坏,因此就需要使用 非极大抑制 的方法来筛选出最优结果,说

    2024年02月09日
    浏览(32)
  • 【数字图像处理】边缘检测

    边缘检测是一种图像处理技术,旨在标识和定位数字图像中的边缘和轮廓。 边缘是图像中灰度值变化明显的位置 ,通常是物体的边缘或表面的变化。通过边缘检测算法,可以将图像中的物体和背景分离出来,从而实现目标检测、图像分割、计算机视觉和机器人视觉等应用。

    2024年02月02日
    浏览(32)
  • 图像处理:边缘检测原理

    很抱歉,前面推导三种边缘检测算子我不是很满意就发出去了,现在以我的知识储备看他们还是有着很大的问题,我潜下心的找资料,看视频,就是为了将我的基础打牢,所以,我在这一篇当中好好的抠细节,毕竟从实际的应用上来说,这是我的学习笔记,再怎么也不能糊弄

    2024年02月06日
    浏览(35)
  • 数字图像处理:图像分割——边缘检测与区域分割

    1.图像分割:根据图像的某些局部特征(灰度级、纹理、彩色或统计特征等)的相似性和互斥性,将图像分割成若干子区域,在每个子区域内部具有相似(相同或相近)特性,而相邻子区域的特性互斥。所以图像分割是利用图像局部特征的相似性和互斥性。 2.图像分割方法分

    2024年02月05日
    浏览(28)
  • 图像处理——边缘检测(MATLAB实现)

    实验表明,人眼对图像中边缘的识别不是通过设置阈值来分割的,目标的边缘一般表现为灰度(对彩色图像还包括色度)的特变。对于人类的视觉感知,图像边缘对理解图像内容起到关键作用。在灰度渐变的图像中无法区分其灰度变化的边界,但如果边界灰度有突变,则可以区

    2024年02月03日
    浏览(30)
  • 【图像处理】基于matlab蚁群聚类图像边缘检测

    目录 基于matlab蚁群聚类图像边缘检测 蚁群聚类是一种模拟自然界中蚂蚁群体行为的算法,常用于解决优化问题。该算法可以用于图像处理中的边缘检测。下面给出一个基于MATLAB的蚁群聚类图像边缘检测的示例代码。 我们首先读入待处理图像,并将其转换为灰度图像。然后,

    2023年04月22日
    浏览(41)
  • 图像处理之梯度及边缘检测算子

    梯度是一个量变化的速度,在数学中通常使用求导、求偏导获取梯度或者某一方向上的梯度。 在数字图像中梯度可以看为像素值分别在x,y方向上的变化速度,因为数字图像的离散型,以及像素是最小处理单元的特性,求数字图像的梯度时,不需要求导,只需要进行加减运算即

    2024年02月16日
    浏览(34)
  • 图像处理技术:数字图像分割 ------ 图像分割、边界分割(边缘检测)、区域分割

    是指根据灰度、彩色、空间纹理、几何形状等特征把图像划分 成若干个互不相交的区域,使得这些特征在同一区域内表现出一致 性或相似性,而在不同区域间表现出明显的不同 分割出来的区域应该同时满足:  (1)分割出来的图像区域的均匀性和连通性。 • 均匀性是指该

    2024年02月04日
    浏览(35)
  • ZYNQ图像处理(7)——sobel边缘检测

    所谓边缘是指其周围像素灰度急剧变化的那些象素的集合,它是图像最基本的特征。边缘存在于目标、背景和区域之间,所以,它是图像分割所依赖的最重要的依据。由于边缘是位置的标志,对灰度的变化不敏感,,因此,边缘也是图像匹配的重要的特征。边缘检测和区域划分

    2024年02月05日
    浏览(45)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包