import numpy as np
import cv2
img = cv2.imread("img_.jpg",0)
# Creat a binary image
threshold = 0
for i in range(0, img.shape[0]):
for j in range(0, img.shape[1]):
threshold += img[i][j]
threshold = int(threshold / (img.shape[0] * img.shape[1]))
img_binary = np.zeros(img.shape)
for i in range(0, img.shape[0]):
for j in range(0, img.shape[1]):
if img[i][j] >= threshold:
img_binary[i][j] = 255
else:
img_binary[i][j] = 0
cv2.imwrite("img_binary.jpg", img_binary)
# Erosion
img_before_erosion = img_binary
img_after_erosion = np.ones(img.shape) * 255
erosion_kernel = np.array([1,1])
for i in range(0, img_binary.shape[0]):
for j in range(1, img_binary.shape[1]):
if img_before_erosion[i][j - 1] * erosion_kernel[0] == 0 and img_before_erosion[i][j] * erosion_kernel[1] == 0:
img_after_erosion[i][j - 1] = 0
else:
img_after_erosion[i][j - 1] = 255
cv2.imwrite("img_after_erosion.jpg", img_after_erosion)
# Dilation
img_before_dilation = img_binary
img_after_dilation = np.ones(img.shape) * 255
dilation_kernel = np.array([1,1])
for i in range(0, img_binary.shape[0]):
for j in range(1, img_binary.shape[1]):
if img_before_dilation[i][j - 1] * dilation_kernel[0] == 0 or img_before_dilation[i][j] * dilation_kernel[1] == 0:
img_after_dilation[i][j - 1] = 0
else:
img_after_dilation[i][j - 1] = 255
cv2.imwrite("img_after_dilation.jpg", img_after_dilation)
# Opening
img_before_opening = img_after_erosion
img_after_opening = np.ones(img.shape) * 255
dilation_kernel = np.array([1,1])
for i in range(0, img_binary.shape[0]):
for j in range(1, img_binary.shape[1
Python 图像处理形态学(Image processing Morphology)
最新推荐文章于 2023-08-22 20:38:28 发布