zoukankan      html  css  js  c++  java
  • opencv 边缘检测原理

    只是实现一下,暂不考虑效率

     1 import cv2 as cv
     2 import numpy as np
     3 import math
     4 
     5 # 从源码层面实现边缘检测
     6 img = cv.imread('../images/face.jpg', flags=1)  # flags=1读取为彩色,flags=0读取为灰度
     7 h, w = img.shape[:2]
     8 gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
     9 dst = np.zeros((h, w, 1), np.uint8)
    10 # 1.sobel 算子模板
    11 # [1  2  1         [1  0  -1
    12 #  0  0  0          2  0  -2
    13 #  -1 -2 -1]        1  0  -1]
    14 # 2.图片卷积
    15 # [1 2 3 4] [a b c d] ->  a*1+b*2+c*3+d*4=dst
    16 # 3.阈值判决
    17 # sqrt(a*a+b*b) = f > th
    18 
    19 for i in range(h-2):
    20     for j in range(w-2):
    21         gy = gray[i, j] + gray[i, j+1]*2 + gray[i, j+2] - gray[i+2, j] - gray[i+2, j+1]*2 - gray[i+2, j+2]
    22         gx = gray[i, j] + gray[i+1, j]*2 + gray[i+2, j] - gray[i, j+2] - gray[i+1, j+2]*2 - gray[i+2, j+2]
    23         grad = math.sqrt(gx*gx+gy*gy)
    24         if grad > 100:  # 阈值假设为100
    25             dst[i, j] = 255
    26         else:
    27             dst[i, j] = 0
    28 
    29 cv.imshow('img1', img)
    30 cv.imshow('img2', dst)
    31 cv.waitKey(0)

    效果

  • 相关阅读:
    mysql面试知识点
    计算机网络
    BFS
    拓扑排序
    双指针
    回溯算法
    hash表 算法模板和相关题目
    桶排序及其应用
    滑动窗口
    贪心算法
  • 原文地址:https://www.cnblogs.com/MC-Curry/p/10414617.html
Copyright © 2011-2022 走看看