卷積核的效果--垂直、水平邊緣檢測~玩
阿新 • • 發佈:2018-11-15
import matplotlib.pyplot as plt
import cv2, numpy as np
imgpath = '/.jpg'
def conv3_3(img, i, j, filt, result): ''' 對img以左上角為i,j的位置做3X3的卷積 ''' ans = 0 for ii in range(3): for jj in range(3): ans = ans + filt[ii, jj] * img[i+ii,j+jj,0] ans = ans + filt[ii, jj] * img[i+ii,j+jj,1] ans = ans + filt[ii, jj] * img[i+ii,j+jj,2] result[i][j] = ans def conv(gray_img, filt): n, m = gray_img.shape[:2] result = np.zeros((n - 3, m - 3)) print('result.shape', result.shape) for i in range(0, n - 3): for j in range(0, m - 3): conv3_3(gray_img, i, j, filt, result) result = result.astype('uint8') return result
gray_img = cv2.imread(imgpath) print(gray_img.shape) #(341, 432) filt1 = np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]]) filt2 = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]]) filt3 = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]]) filt4 = np.array([[-1, -1, -1], [0, 0, 0], [1, 1, 1]]) r1 = conv(gray_img, filt1) r2 = conv(gray_img, filt2) plt.figure(1) plt.subplot(121, title='vertical 1,0,-1') plt.imshow(r1) plt.subplot(122, title='vertical -1,0,1') plt.imshow(r2) r3 = conv(gray_img, filt3) r4 = conv(gray_img, filt4) plt.figure(2) plt.subplot(121, title='horizontal 1,0,-1') plt.imshow(r3) plt.subplot(122, title='horizontal -1,0,1') plt.imshow(r4) plt.figure(3) plt.imshow(gray_img)