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

如何使用Python统计语义分割输出图像的类别数量

语义分割图像类别统计实现方案

你当前使用的直接统计唯一像素值的方法,会受图像混色伪影干扰得到错误结果,可通过颜色相似度聚类+小像素簇过滤的逻辑实现需求,具体实现如下:

核心逻辑

  • 计算像素RGB值的欧氏距离判断相似性,距离小于设定阈值则归为同一类别
  • 统计每个类别的像素总数量,过滤掉数量小于设定阈值的小杂色簇

依赖安装

pip install pillow numpy

完整代码

from PIL import Image
import numpy as np

def count_segment_classes(img_path, color_threshold=20, min_pixels=100):
    img = Image.open(img_path).convert('RGB')
    img_arr = np.array(img)
    pixels = img_arr.reshape(-1, 3)
    
    class_colors = []
    class_counts = []
    
    for pixel in pixels:
        matched = False
        for idx, cls_color in enumerate(class_colors):
            # 计算RGB通道欧氏距离
            color_dist = np.linalg.norm(pixel - cls_color)
            if color_dist < color_threshold:
                class_counts[idx] += 1
                matched = True
                break
        if not matched:
            class_colors.append(pixel)
            class_counts.append(1)
    
    # 过滤像素数不足的杂色簇
    valid_classes = [(color, cnt) for color, cnt in zip(class_colors, class_counts) if cnt >= min_pixels]
    return len(valid_classes), valid_classes

if __name__ == '__main__':
    class_count, class_detail = count_segment_classes(
        img_path = "替换为你的图像路径",
        color_threshold = 20, # 颜色相似度阈值,值越大归为同一类的门槛越低
        min_pixels = 50 # 最小像素阈值,小于该值的颜色簇会被判定为杂色过滤
    )
    print(f"实际类别数量:{class_count}")
    print("各类别信息:")
    for color, cnt in class_detail:
        print(f"代表色RGB:{list(color)},像素总数:{cnt}")

参数调整说明

  • color_threshold:颜色区分度高的场景可适当调大(推荐范围10~30),颜色相近的场景调小
  • min_pixels:根据图像分辨率调整,需过滤的杂点越小则值越小(推荐范围10~图像总像素的0.1%)

示例图像:
示例图像

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 15:36:07