You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Scikit-Image SLIC分割结果图中显示类别标签值

给SLIC分割结果添加类别标签编号

要在分割结果图的每个类别中心显示标签编号,你可以通过计算每个分割区域的中心坐标,再用Matplotlib的文本标注功能实现。以下是修改后的完整代码:

import matplotlib.pyplot as plt
from skimage.segmentation import slic
from skimage import color
import numpy as np

# 假设img_blurred、img_rounded、img_blurred_normalized已提前定义
img_bounds = slic(img_blurred,          # 滤波后的输入图像
                  n_segments=25,
                  compactness=1,
                  start_label=0)

plt.figure()
plt.gray()
plt.subplot(121)
plt.imshow(img_rounded)                 # 输入图像
plt.subplot(122)
# 绘制带颜色的分割结果
plt.imshow(color.label2rgb(img_bounds, img_blurred_normalized, alpha=0.5))

# 获取所有唯一的标签值
unique_labels = np.unique(img_bounds)

# 遍历每个标签,计算中心并标注
for label in unique_labels:
    # 找到当前标签对应的所有像素坐标
    y_coords, x_coords = np.where(img_bounds == label)
    # 计算中心坐标(取平均值)
    center_y = np.mean(y_coords)
    center_x = np.mean(x_coords)
    # 在中心位置标注标签编号,设置合适的字体颜色和大小
    plt.text(center_x, center_y, str(label), 
             color='white',  # 白色文字适配深色分割区域;若背景偏亮可改用'black'
             fontsize=10,
             ha='center', va='center')  # 文字居中对齐

plt.show()

关键部分说明:

  • 计算中心坐标:用np.where()提取当前标签对应的所有像素的y、x坐标,再通过np.mean()计算平均值得到区域中心。
  • 文本标注:plt.text()的前两个参数是标注位置的x、y坐标(注意和numpy返回的y、x顺序相反);ha='center'和va='center'确保文字在中心位置对齐;字体颜色可根据分割图的背景色调调整,保证可读性。

内容的提问来源于stack exchange,提问作者Ondra Burkot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 22:30:57