python获取图像的最大连通区域

本文介绍了如何使用Python的skimage库处理二值图像,包括图像读取、连通区域标记、最大区域寻找,并展示了结果。通过measure模块的label和regionprops函数,实现了图像中最大连通区域的提取。
摘要由CSDN通过智能技术生成

二值图像最大连通区域获取

图像读取

from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
from skimage import measure

# 图像读取
imagePath = r'./008_mask.png'
img = Image.open(imagePath).resize((512, 512))
img = np.array(img)  
img[img != 0] = 1  # 图像二值化
plt.subplot(1, 3, 1)
plt.imshow(img)

# 图像实例化
img = measure.label(img, connectivity=2)
props = measure.regionprops(img)
plt.subplot(1, 3, 2)
plt.imshow(img)

# 最大区域获取
max_area = 0
max_index = 0
# props只包含像素值不为零区域的属性,因此index要从1开始
for index, prop in enumerate(props, start=1):
    if prop.area > max_area:
        max_area = prop.area
        # index 代表每个联通区域内的像素值;prop.area代表相应连通区域内的像素个数
        max_index = index

img[img != max_index] = 0
img[img == max_index] = 1

# 结果显示
plt.subplot(1, 3, 3)
plt.imshow(img)
plt.show()

结果显示

在这里插入图片描述
注: 这里不在给出下面两个函数的用法, 想了解的可以自行csdn

img = measure.label(img, connectivity=2)
props = measure.regionprops(img)
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值