删除小块区域
有些时候,我们只需要一些大块区域,那些零散的、小块的区域,我们就需要删除掉,
则可以使用morphology子模块的remove_small_objects函数。
让书和背景分离
对图片做了二值化,腐蚀,膨胀操作
使用remove_small_objects函数
import numpy
import numpy as np
import scipy.ndimage as ndi
from skimage import morphology
import matplotlib.pyplot as plt
import cv2
#编写一个函数来生成原始二值图像
def microstructure(img_path):
# 将图像灰度化
img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
# 让书和背景分离,这里我们将图片二值化
retVal, image = cv2.threshold(img, 30, 230, cv2.THRESH_BINARY)
# 开始进行腐蚀操作
corrosion_img = cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 5)) ##腐蚀预处理,确定处理核的大小,矩阵操作
img3 = cv2.erode(image, corrosion_img, iterations=10) # 进行腐蚀操作
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
expand_pic = cv2.dilate(img3, kernel)
pic_matrix = numpy.array(expand_pic)
height, width = expand_pic.shape
for i in range(height):
for j in range(width):
pic_matrix[i, j] = 255 - img[i, j]
return pic_matrix > pic_matrix.mean()
img_path = './sample1.jpg'
data = microstructure(img_path) #生成测试图片
dst=morphology.remove_small_objects(data,min_size=220000)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4))
ax1.imshow(data, plt.cm.gray, interpolation='nearest')
ax2.imshow(dst,plt.cm.gray,interpolation='nearest')
fig.tight_layout()
plt.show()