python自程式設計序實現——robert運算元、sobel運算元、Laplace運算元進行影象邊緣提取
阿新 • • 發佈:2018-11-03
實現思路:
1,將傳進來的圖片矩陣用運算元進行卷積求和(卷積和取絕對值)
2,用新的矩陣(與原圖一樣大小)去接收每次的卷積和的值
3,卷積圖片所有的畫素點後,把新的矩陣資料型別轉化為uint8
注意:
必須對求得的卷積和的值求絕對值;矩陣資料型別進行轉化。
完整程式碼:
import cv2 import numpy as np # robert 運算元[[-1,-1],[1,1]] def robert_suanzi(img): r, c = img.shape r_sunnzi = [[-1,-1],[1,1]] for x in range(r): for y in range(c): if (y + 2 <= c) and (x + 2 <= r): imgChild = img[x:x+2, y:y+2] list_robert = r_sunnzi*imgChild img[x, y] = abs(list_robert.sum()) # 求和加絕對值 return img # # sobel運算元的實現 def sobel_suanzi(img): r, c = img.shape new_image = np.zeros((r, c)) new_imageX = np.zeros(img.shape) new_imageY = np.zeros(img.shape) s_suanziX = np.array([[-1,0,1],[-2,0,2],[-1,0,1]]) # X方向 s_suanziY = np.array([[-1,-2,-1],[0,0,0],[1,2,1]]) for i in range(r-2): for j in range(c-2): new_imageX[i+1, j+1] = abs(np.sum(img[i:i+3, j:j+3] * s_suanziX)) new_imageY[i+1, j+1] = abs(np.sum(img[i:i+3, j:j+3] * s_suanziY)) new_image[i+1, j+1] = (new_imageX[i+1, j+1]*new_imageX[i+1,j+1] + new_imageY[i+1, j+1]*new_imageY[i+1,j+1])**0.5 # return np.uint8(new_imageX) # return np.uint8(new_imageY) return np.uint8(new_image) # 無方向運算元處理的影象 # Laplace運算元 # 常用的Laplace運算元模板 [[0,1,0],[1,-4,1],[0,1,0]] [[1,1,1],[1,-8,1],[1,1,1]] def Laplace_suanzi(img): r, c = img.shape new_image = np.zeros((r, c)) L_sunnzi = np.array([[0,-1,0],[-1,4,-1],[0,-1,0]]) # L_sunnzi = np.array([[1,1,1],[1,-8,1],[1,1,1]]) for i in range(r-2): for j in range(c-2): new_image[i+1, j+1] = abs(np.sum(img[i:i+3, j:j+3] * L_sunnzi)) return np.uint8(new_image) img = cv2.imread('1.jpg', cv2.IMREAD_GRAYSCALE) cv2.imshow('image', img) # # robers運算元 out_robert = robert_suanzi(img) cv2.imshow('out_robert_image', out_robert) # sobel 運算元 out_sobel = sobel_suanzi(img) cv2.imshow('out_sobel_image', out_sobel) # Laplace運算元 out_laplace = Laplace_suanzi(img) cv2.imshow('out_laplace_image', out_laplace) cv2.waitKey(0) cv2.destroyAllWindows()