ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

5.2 数字图像处理——Canny边缘检测Python实现

2021-03-28 17:04:39  阅读:188  来源: 互联网

标签:5.2 plt img Python 数字图像处理 edge np import cv


1. 直接调用 OpenCV函数

import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt

## 重点
img = cv.imread('pic/notebook500x333.jpg', 0)
img_edge = cv.Canny(img, 20, 200)
plt.imshow(img_edge, cmap='gray')
plt.show()

2. 效果

从左到右依次为原图、OpenCV直接调用、自己实现效果。

3. 自己实现

import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt

def show(img):
    if img.ndim == 2:
        plt.imshow(img, cmap='gray')
    else:
        img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
        plt.imshow(img)
    plt.show()


img = cv.imread('pic/notebook500x333.jpg', 0)

# 1. 平滑
img_blur = cv.GaussianBlur(img, (5,5), 2)

# 2. 计算梯度
gradx = cv.Sobel(img_blur, cv.CV_64F, 1, 0)
grady = cv.Sobel(img_blur, cv.CV_64F, 0, 1)
R = np.abs(gradx) + np.abs(grady)
T = np.arctan(grady / (gradx + 1e-3))

# 3. 非极大值抑制,细化边缘
h, w = R.shape
img_thin = np.zeros_like(R)

for i in range(1, h-1):
    for j in range(1, w-1):
        theta = T[i,j]
        if -np.pi / 8 <= theta < np.pi / 8:
            if R[i,j] == max([R[i,j], R[i,j-1], R[i, j+1]]):
                img_thin[i,j] = R[i,j]
        elif -3 * np.pi / 8 <= theta < -np.pi / 8:
            if R[i,j] == max([R[i,j], R[i-1,j+1], R[i+1,j-1]]):
                img_thin[i,j] = R[i,j]
        elif np.pi / 8 <= theta < 3 * np.pi / 8:
            if R[i,j] == max([R[i,j], R[i-1,j-1], R[i+1,j+1]]):
                img_thin[i,j] = R[i,j]      
        else:
            if R[i,j] == max([R[i,j], R[i-1,j], R[i+1,j]]):
                img_thin[i,j] = R[i,j]
                
# 双阈值抑制

th1 = 5
th2 = 30
maxv = 255

img_edge = np.zeros_like(img_thin)

h, w = img_thin.shape
for i in range(1, h - 1):
    for j in range(1, w - 1):
        if img_thin[i,j] >= th2:
            img_edge[i,j] = maxv
        elif img_thin[i,j] > th1:
            around = img_thin[i-1:i+2, j-1:j+2]
            if around.max() >= th2:
                img_edge[i,j] = maxv
        
show(img_edge)

说明:

  1. 未经许可,谢绝转载。
  2. 本教程为《数字图像处理Python OpenCV实战》的配套代码相关内容。
    免费视频教程为0-6章(标题号≤6),可在此处点击观看。
    所有课件及源代码可在此处下载:
    链接:https://pan.baidu.com/s/198PySe_vebO3e06idHSQ6g
    提取码:11o4
    有问题可在QQ群(1079300899)指出,进群答案:数字图像处理。在本文评论指出可能导致回复很晚。

标签:5.2,plt,img,Python,数字图像处理,edge,np,import,cv
来源: https://www.cnblogs.com/forcekeng/p/14589122.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有