python -opencv形态学操作
1.服饰和膨胀
2.开运算和闭运算
3.礼帽运算和黑帽运算
1.服饰和膨胀
opencv 腐蚀通过cv2.erode实现,膨胀通过cv2.dilate实现,看一下下面代码:
from ctypes.wintypes import SIZE
from multiprocessing.pool import IMapUnorderedIterator
import cv2
import copy
import math
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import ospath=r'D:\learn\photo\cv\dige.png'img=cv2.imread(path)def cv_show(name,img):cv2.imshow(name,img)#cv2.waitKey(0),接收0,表示窗口暂停cv2.waitKey(0)#销毁所有窗口cv2.destroyAllWindows()#cv_show('img',img)kernel=np.ones((3,3),np.uint8)dila_img=cv2.dilate(img,kernel=kernel,iterations=1)#cv_show('dila_img',dila_img)kernel=np.ones((3,3),np.uint8)ero_img=cv2.erode(img,kernel=kernel,iterations=1)#cv_show('dila_img',ero_img)plt.figure(figsize=(400,600))plt.subplot(131)
plt.imshow(img)
plt.title('img')plt.subplot(132)
plt.imshow(dila_img)
plt.title('dila_img')
plt.subplot(133)
plt.imshow(ero_img)
plt.title('ero_img')
plt.show()
os.system("pause")
运行结果如下:
2.开运算和闭运算
1.开运算:先腐蚀,后膨胀
# 开运算,先腐蚀,后膨胀
result = cv2.morphologyEx(img, op=cv2.MORPH_OPEN,kernel=kernel, iterations=1)
2.闭运算:先膨胀,后腐蚀
result = cv2.morphologyEx(img, op=cv2.MORPH_CLOSE,kernel=kernel, iterations=1)
3.礼帽运算和黑帽运算
处理图像:
import copy
import math
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import osimport cv2'''礼帽运算:原图-开运算
黑帽运算:闭运算-原图'''path=r'D:\learn\photo\cv\dige.png'img=cv2.imread(path)kernel=np.ones((5,5),np.uint8)def cv_show(name,img):cv2.imshow(name,img)#cv2.waitKey(0),接收0,表示窗口暂停cv2.waitKey(0)#销毁所有窗口cv2.destroyAllWindows()tphat=cv2.morphologyEx(img,cv2.MORPH_TOPHAT,kernel)blhat=cv2.morphologyEx(img,cv2.MORPH_BLACKHAT,kernel)cv_show('tphat',tphat)
cv_show('blhat',blhat)
os.system("pause")