Python图像处理:形态学操作
来源:DeepHub IMBA 本文约1400字,建议阅读5分钟 形态学的操作主要是去除影响图像形状和信息的噪声。形态学运算在图像分割中非常有用,可以得到无噪声的二值图像。
形态学方法
膨胀
import numpy as np
import imutils
import cv2#reading the input image
img = cv2.imread('thumb.png') #reads the image
#cv2.imwrite('Input_image.jpg',image)
#Resizing the image
scale_percent = 70
width = int(img.shape[1] * scale_percent / 100)
height = int(img.shape[0] * scale_percent / 100)
dim = (width, height)
# resize the input image
image = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)
kernel = np.ones((1,1), dtype = "uint8")/9
dilation = cv2.dilate(image,kernel,iterations = 1)
cv2.imwrite('dilation.jpg', dilation)
kernel = np.ones((2,2), dtype = "uint8")/9
dilation = cv2.dilate(image,kernel,iterations = 1)
cv2.imwrite('dilation.jpg', dilation)
kernel = np.ones((2,2), dtype = "uint8")/9
dilation = cv2.dilate(image,kernel,iterations = 3)
cv2.imwrite('dilation.jpg', dilation)
kernel = np.ones((2,2), dtype = "uint8")/9
dilation = cv2.dilate(image,kernel,iterations = 5)
cv2.imwrite('dilation.jpg', dilation)
kernel = np.ones((3,3), dtype = "uint8")/9
dilation = cv2.dilate(image,kernel,iterations = 2)
cv2.imwrite('dilation.jpg', dilation)
侵蚀
import numpy as np
import imutils
import cv2
#reading the input image
img = cv2.imread('thumb.png')
#cv2.imwrite('Input_image.jpg',image)
#Resizing the image
scale_percent = 70
width = int(img.shape[1] * scale_percent / 100)
height = int(img.shape[0] * scale_percent / 100)
dim = (width, height)
# resize the input image
image = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)
kernel = np.ones((1,1), dtype = "uint8")/9
erosion = cv2.erode(image, kernel, iterations = 1)
cv2.imwrite('erosion.jpg', erosion)
kernel = np.ones((2,2), dtype = "uint8")/9
erosion = cv2.erode(image, kernel, iterations = 2)
cv2.imwrite('erosion.jpg', erosion)
kernel = np.ones((2,2), dtype = "uint8")/9
erosion = cv2.erode(image, kernel, iterations = 3)
cv2.imwrite('erosion.jpg', erosion)
kernel = np.ones((2,2), dtype = "uint8")/9
erosion = cv2.erode(image, kernel, iterations = 5)
cv2.imwrite('erosion.jpg', erosion)
kernel = np.ones((5,5), dtype = "uint8")/9
erosion = cv2.erode(image, kernel, iterations = 2)
cv2.imwrite('erosion.jpg', erosion)
开操作
import numpy as np
import imutils
import cv2
#reading the input image
img = cv2.imread('11.png')
kernel = np.ones((5,5), dtype = "uint8")/9
opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
cv2.imwrite('opening.jpg', opening)
import numpy as np
import imutils
import cv2
#reading the input image
img = cv2.imread('thumb.png')
kernel = np.ones((9,9), dtype = "uint8")/9
closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
cv2.imwrite('closing.jpg', closing)
形态学梯度
import numpy as np
import imutils
import cv2
#reading the input image
img = cv2.imread('g1.png')
kernel = np.ones((6,6), dtype = "uint8")/9
gradient = cv2.morphologyEx(img, cv2.MORPH_GRADIENT, kernel)
cv2.imwrite('gradient.jpg', gradient)
总结
编辑:文婧
评论