让书和背景分离/去除大区域中小的连通区域(python实现)

删除小块区域

有些时候,我们只需要一些大块区域,那些零散的、小块的区域,我们就需要删除掉,

则可以使用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()

 

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值