【圖像處理3】laplace算子邊緣檢測

# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
import cv2

"""
laplace算子作爲邊緣檢測,是各方向的二階導數

其卷積模板爲: 
0   1   0
1   -4  1
0   1   0

或拓展模板
1   1   1
1   -8  1
1   1   1


"""
path = '/Volumes/項目/10.Deep Learning/06.Severstal Steel Defect Detection/00.data/other_img/'
img  = cv2.imread(path + 'lena.jpg')

img_gray       = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
img_gray_array = np.array(img_gray)

#3 * 3 卷積
def conv2(img, H, W, kernel):

    k_h = kernel.shape[0]
    k_w = kernel.shape[1]

    res = np.zeros([H,W])
    for i in range(0, H - (k_h - 1)):
        for j in range(0,  W - (k_w - 1)):

            temp = img[i:i + k_h, j:j + k_w]
            temp = np.multiply(temp,kernel) #numpy的multiply是對應元素相乘
            res[i][j] = temp.sum()

    return (res)


#laplace_kernel = np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]])
laplace_kernel = np.array([[1, 1, 1], [1, -8, 1], [1, 1, 1]])

res = conv2(img_gray_array, img_gray_array.shape[0], img_gray_array.shape[1], laplace_kernel)

plt.imshow(res, cmap='gray')
plt.show()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章