形态学梯度调用
import cv2
import numpy as np
# 读图
# img = cv2.imread('./output2/2.jpg', 0)
# # 设置核
# kernel = np.ones((5, 5), np.uint8)
# # 形态学梯度调用
# gradient = cv2.morphologyEx(img, cv2.MORPH_GRADIENT, kernel)
#
# # 显示效果
# cv2.imshow('src', img)
# cv2.imshow('result', gradient)
# cv2.waitKey()
img = cv2.imread('./output1/3.jpg', cv2.IMREAD_UNCHANGED)
# 设置核
kernel = np.ones((3, 3), np.uint8)
# 形态学梯度调用
erosion = cv2.erode(img, kernel)
# 显示效果
cv2.imshow('src', img)
cv2.imshow('result', erosion)
cv2.waitKey()
开运算
不断的开运算是没有关系的
import cv2
import numpy as np
# 读图
img = cv2.imread('./output1/2.jpg', 0)
# 设置核
# kernel = np.ones((5, 5), np.uint8)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(2,2))
# 开运算
opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
# 显示效果
cv2.imshow('src', img)
cv2.imshow('result', opening)
cv2.waitKey()
# def open_demo(image):
# # print(image.shape)
# gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)
# ret , binary = cv.threshold(gray,0,255,cv.THRESH_BINARY|cv.THRESH_OTSU)
# # kernel = np.ones((5,5),np.uint16)
# kernel = cv.getStructuringElement(cv.MORPH_RECT,(5,5))
# dst = cv.morphologyEx(binary,cv.MORPH_OPEN,kernel)
# cv.imshow("open_demo",dst)
#
# img = cv.imread('./output2/2.jpg', 0)
# open_demo(img)
自实现开运算
主要是通过不同的系数来实现腐蚀和膨胀的结合
import cv2
from PIL import Image
import numpy as np
img = cv2.imread('./output1/0.jpg', cv2.IMREAD_UNCHANGED)
# 设置核
kernel = np.ones((2, 2), np.uint8)
# 形态学梯度调用
erosion = cv2.erode(img, kernel, iterations=2)
kernel = np.ones((2, 2), np.uint8)
dilate = cv2.dilate(erosion, kernel, iterations=1)
# 显示效果
# v2.imshow('src', img)
# cv2.imshow('result', erosion)
# cv2.imshow('result1', dilate)
cv2.imwrite("./0x.jpg", dilate)
cv2.waitKey()
黑帽
import cv2
import numpy as np
#读图
img = cv2.imread('./output2/2.jpg',0)
#设置核
kernel = np.ones((5,5),np.uint8)
#黑帽调用
blackhat = cv2.morphologyEx(img, cv2.MORPH_BLACKHAT, kernel)
#显示效果
cv2.imshow('src',img)
cv2.imshow('show',blackhat)
cv2.waitKey()