图像读取
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)