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

如何利用掩码区域获取超像素的质心?

获取SLIC超像素的质心坐标

嘿,作为同样折腾过SLIC超像素的开发者,我来给你分享两种靠谱的方法搞定质心坐标,完美适配你现有的代码~

方法一:用skimage内置的regionprops(最省心)

skimage的measure.regionprops工具专门用来提取区域的各种属性,质心就是其中之一,用它一步到位:

from skimage import measure

# 假设你已经得到了segments = slic(...)
regions = measure.regionprops(segments)

# 遍历每个超像素区域,获取质心
for region in regions:
    # 注意:centroid返回的是(y, x)坐标顺序哦
    centroid_y, centroid_x = region.centroid
    print(f"超像素{region.label}的质心坐标:({centroid_x:.2f}, {centroid_y:.2f})")

这个方法不用你自己写mask循环,直接从segments里提取所有区域的属性,效率高还不容易出错,顺便还能拿到区域面积、外接矩形等其他有用属性。

方法二:手动计算质心(适合理解原理)

如果你想自己实现计算逻辑,也可以基于你现有的循环改造,对每个超像素的所有像素坐标求平均:

import numpy as np

# 先生成图像的坐标网格
y_coords, x_coords = np.indices(image.shape[:2])

# 遍历每个超像素
for v in np.unique(segments):
    # 获取当前超像素的像素掩码
    mask = segments == v
    # 计算x和y方向的均值,就是质心
    centroid_x = np.mean(x_coords[mask])
    centroid_y = np.mean(y_coords[mask])
    print(f"超像素{v}的质心坐标:({centroid_x:.2f}, {centroid_y:.2f})")
    
    # 你原来的A通道均值计算可以直接放在这里
    A = mean_achannel(img, mask)

这里要注意np.indices生成的是(y, x)格式的网格,所以求平均后得到的质心顺序是(y, x),如果需要(x, y)的话交换一下数值顺序就行。

小补充

如果需要把所有质心存在列表里方便后续使用,可以这样写:

# 转成(x, y)格式的质心列表
centroids = [(r.centroid[1], r.centroid[0]) for r in regions]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:06:16