在Python中应用scipy.ndimagebinary_fill_holes()函数进行图像二值化和孔洞填充
发布时间:2023-12-28 07:58:26
在Python中,我们可以使用scipy库的ndimage模块来进行图像处理。其中的binary_fill_holes()函数可以对图像进行二值化和孔洞填充。
首先,我们需要导入所需的库和模块:
import numpy as np from PIL import Image from scipy import ndimage
然后,我们可以加载一张图像,并将其转换为灰度图像,这里使用PIL库来加载和转换图像:
# 读取图像并转换为灰度图像
image = Image.open('image.jpg').convert('L')
接下来,我们可以将灰度图像转换为二值图像,这里使用了一个简单的阈值方法,小于阈值的像素设为0(黑色),大于阈值的像素设为255(白色):
# 转换为二值图像 threshold = 128 image_binary = np.array(image) > threshold
现在,我们可以使用binary_fill_holes()函数来填充图像中的孔洞。这个函数会找到图像中白色的连通区域,并将其中的孔洞填充为白色。黑色的像素被视为孔洞。
# 孔洞填充 image_filled = ndimage.binary_fill_holes(image_binary)
最后,我们可以将二值化和孔洞填充后的图像保存下来:
# 保存图像
image_filled = Image.fromarray(image_filled.astype(np.uint8) * 255)
image_filled.save('filled_image.jpg')
完整的代码如下:
import numpy as np
from PIL import Image
from scipy import ndimage
# 读取图像并转换为灰度图像
image = Image.open('image.jpg').convert('L')
# 转换为二值图像
threshold = 128
image_binary = np.array(image) > threshold
# 孔洞填充
image_filled = ndimage.binary_fill_holes(image_binary)
# 保存图像
image_filled = Image.fromarray(image_filled.astype(np.uint8) * 255)
image_filled.save('filled_image.jpg')
这段代码将会加载一张名为'image.jpg'的图像,对其进行二值化和孔洞填充,并将结果保存为'filled_image.jpg'。通过调整阈值和输入图像,你可以得到不同的输出效果。
