OpenCV:图像canny边缘检测

1 介绍

Canny 边缘检测是一种非常流行的边缘检测算法,是John F.Canny 在1986 年提出的。它是一个有很多步构成的算法。在OpenCV 中只需要一个函数:cv2.Canny(),就可以完成以上几步。让我们看如何使用这个函数。这个函数的第一个参数是输入图像。第二和第三个分别是minVal 和maxVal。第三个参数设置用来计算图像梯度的Sobel卷积核的大小,默认值为3。最后一个参数是L2gradient,它可以用来设定求梯度大小的方程。如果设为True,就会使用我们上面提到过的方程,否则使用方程:Edge?Gradient (G) = |G2x| + |G2y|代替,默认值为False。

2 代码 

import cv2 as cv
import numpy as np
import os
import matplotlib.pylab as plt

sigma = 0.33
def edge(img):
    # median = np.mean(np.array(img))
    # # print(median)
    # lower = int((1.0 - sigma)*median)
    # if lower < 0:lower = 0
    # upper = int((1.0 + sigma)*median)
    # if upper > 255:upper = 255

    # 高斯模糊,降低噪声
    blurred = cv.GaussianBlur(img, (3, 3), 0)
    # 灰度图像
    gray = cv.cvtColor(blurred, cv.COLOR_RGB2GRAY)
    # 图像梯度
    xgrad = cv.Sobel(gray, cv.CV_16SC1, 1, 0)
    ygrad = cv.Sobel(gray, cv.CV_16SC1, 0, 1)
    # 计算边缘
    # 50和150参数必须符合1:3或者1:2
    edge_output = cv.Canny(xgrad, ygrad, 20, 60)
    # 图一
    cv.imshow("edge", edge_output)
    cv.imwrite('edge.jpg',edge_output)

    dst = cv.bitwise_and(img, img, mask=edge_output)
    # 图二(彩色)
    cv.imshow('cedge', dst)
    cv.imwrite('cedge.jpg',dst)


def edge_for_images(source_path,save_path):
    if not os.path.exists(source_path):
        return
    if not os.path.exists(save_path):
        os.makedirs(save_path)
    for file in os.listdir(source_path):
        print(file)
        img = cv.imread(os.path.join(source_path,file))
        # 高斯模糊,降低噪声
        blurred = cv.GaussianBlur(img, (3, 3), 0)
        # 灰度图像
        gray = cv.cvtColor(blurred, cv.COLOR_RGB2GRAY)
        # gray = blurred
        # 图像梯度
        xgrad = cv.Sobel(gray, cv.CV_16SC1, 1, 0)
        ygrad = cv.Sobel(gray, cv.CV_16SC1, 0, 1)
        # 计算边缘
        # 50和150参数必须符合1:3或者1:2
        edge_output = cv.Canny(xgrad, ygrad, 15, 35)
        # print(edge_output)
        # 图一
        # cv.imshow("edge", edge_output)
        cv.imwrite(os.path.join(save_path,file), edge_output)

if __name__ == '__main__':
    edge_for_images('H:\\LONGBO\\CD\\gt','H:\\LONGBO\\CD\\gt(edge)')

3 效果 

这里只展示一张图:

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值