import cv2 import numpy as np img = cv2.imread('DataPreprocessing/img/dige.png') cv2.imshow("img", img) cv2.waitKey(0) cv2.destroyAllWindows()
dige.png原圖1展示(註: 沒有原圖的可以截圖下來保存本地。
#腐蝕1輪次之後~ (iterations = 1)
kernel = np.ones((3, 3), np.uint8) erosion = cv2.erode(img, kernel, iterations=1) cv2.imshow('erosion', erosion) cv2.waitKey(0) cv2.destroyAllWindows()
腐蝕結果展示圖2:
腐蝕圓多次的效果,以及腐蝕原理
pie = cv2.imread('DataPreprocessing/img/pie.png') cv2.imshow('pie', pie) cv2.waitKey(0) cv2.destroyAllWindows()
pie.png原圖3:
腐蝕原理, 其中濾波器的大小越大腐蝕的程度越大圖4:
#kernel = np.ones((30, 30), np.uint8) erosion_1 = cv2.erode(pie, kernel, iterations=1) erosion_2 = cv2.erode(pie, kernel, iterations=2) erosion_3 = cv2.erode(pie, kernel, iterations=3) res = np.hstack((erosion_1, erosion_2, erosion_3)) cv2.imshow('res', res) cv2.waitKey(0) cv2.destroyAllWindows()
圓腐蝕三次結果展示圖5:
kernel = np.ones((3, 3), np.uint8) dige_dilate = erosion dige_dilate = cv2.dilate(erosion, kernel, iterations=1) cv2.imshow('dilate', dige_dilate) cv2.waitKey(0) cv2.destroyAllWindows()
膨脹之前圖2,發現線條變粗,跟原圖對比的線條相差無幾,但是沒了那些長須裝的噪音,圖6:
膨脹圓多次的效果,以及膨脹原理與腐蝕相反,有白點的濾波器則濾波器內資料全變為白色。
pie = cv2.imread('DataPreprocessing/img/pie.png') kernel = np.ones((30, 30), np.uint8) dilate_1 = cv2.dilate(pie, kernel, iterations=1) dilate_2 = cv2.dilate(pie, kernel, iterations=2) dilate_3 = cv2.dilate(pie, kernel, iterations=3) res = np.hstack((dilate_1, dilate_2, dilate_3)) cv2.imshow('res', res) cv2.waitKey(0) cv2.destroyAllWindows()
膨脹圓3次的結果展示,圖7:
##二、 開運算與閉運算2.1 開運算# 开:先腐蚀,再膨胀 img = cv2.imread('DataPreprocessing/img/dige.png') kernel = np.ones((5, 5), np.uint8) opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel) cv2.imshow('opening', opening) cv2.waitKey(0) cv2.destroyAllWindows()
圖8:
2.2 閉運算# 闭:先膨胀,再腐蚀 img = cv2.imread('DataPreprocessing/img/dige.png') kernel = np.ones((5, 5), np.uint8) closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel) cv2.imshow('closing', closing) cv2.waitKey(0) cv2.destroyAllWindows()
圖9:
#三、梯度運算拿原圖3的圓,做5次膨脹,5次腐蝕,相減得到其輪廓。# 梯度=膨胀-腐蚀 pie = cv2.imread('DataPreprocessing/img/pie.png') kernel = np.ones((7, 7), np.uint8) dilate = cv2.dilate(pie, kernel, iterations=5) erosion = cv2.erode(pie, kernel, iterations=5) res = np.hstack((dilate, erosion)) cv2.imshow('res', res) cv2.waitKey(0) cv2.destroyAllWindows() gradient = cv2.morphologyEx(pie, cv2.MORPH_GRADIENT, kernel) cv2.imshow('gradient', gradient) cv2.waitKey(0) cv2.destroyAllWindows()得到梯度運算結果
圖10:
#四、禮帽與黑帽4.1禮帽禮帽= 原始輸入-開運算結果
# 礼帽 img = cv2.imread('DataPreprocessing/img/dige.png') tophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel) cv2.imshow('tophat', tophat) cv2.waitKey(0) cv2.destroyAllWindows()得到禮帽結果
圖11:
#4.2 黑帽黑帽= 閉運算-原始輸入######
# 黑帽 img = cv2.imread('DataPreprocessing/img/dige.png') blackhat = cv2.morphologyEx(img, cv2.MORPH_BLACKHAT, kernel) cv2.imshow('blackhat ', blackhat) cv2.waitKey(0) cv2.destroyAllWindows()###得到禮帽結果###圖12:####### ##########
以上是Python+OpenCV之形態學的操作方法是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!