Matplotlib创建语义分割用Cityscapes_Palette_Map离散colormap
实现离散类别映射的Cityscapes/Carla语义分割自定义colormap方法
以下是Python生态下两种常用的实现方案,完全适配0-22类的离散标签到固定颜色的一对一映射需求,不会出现连续cmap的插值混色问题:
方案1:Matplotlib 自定义离散ListedColormap
适用于需要用Matplotlib绘图渲染语义分割结果的场景,ListedColormap是Matplotlib专门提供的离散类别映射接口:
import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap, BoundaryNorm # 按0-22类别顺序排列的Carla语义标签RGB颜色(0-255格式,和Cityscapes标准配色对齐) carla_semantic_colors = [ (0, 0, 0), # 0: Unlabeled (70, 70, 70), # 1: Building (100, 40, 40), # 2: Fence (55, 90, 80), # 3: Other (220, 20, 60), # 4: Pedestrian (153, 153, 153), # 5: Pole (157, 234, 50), # 6: Road line (128, 64, 128), # 7: Road (244, 35, 232), # 8: Sidewalk (107, 142, 35), # 9: Vegetation (0, 0, 142), # 10: Car (102, 102, 156), # 11: Wall (220, 220, 0), # 12: Traffic sign (70, 130, 180), # 13: Sky (81, 0, 81), # 14: Ground (150, 100, 100), # 15: Bridge (230, 150, 140), # 16: Rail track (180, 165, 180), # 17: Guard rail (250, 170, 30), # 18: Traffic light (110, 190, 160), # 19: Static (170, 120, 50), # 20: Dynamic (45, 60, 150), # 21: Water (145, 170, 100) # 22: Terrain ] # 转归一化到[0,1]的格式适配Matplotlib要求 carla_colors_norm = np.array(carla_semantic_colors) / 255.0 # 生成离散cmap cityscapes_cmap = ListedColormap(carla_colors_norm, name='carla_cityscapes') # 定义边界,保证每个整数标签严格对应对应颜色,避免插值偏移 norm = BoundaryNorm(boundaries=np.arange(-0.5, 23, 1), ncolors=cityscapes_cmap.N) # 测试用例 semantic_mask = np.random.randint(0, 23, size=(200, 200)) plt.imshow(semantic_mask, cmap=cityscapes_cmap, norm=norm) plt.axis('off') plt.show()
方案2:Numpy索引直接映射(全场景适配)
不需要依赖Matplotlib,直接生成可用于OpenCV、PIL等库的RGB语义掩码,运算效率更高:
import numpy as np import cv2 # 按0-22类别顺序排列的RGB颜色(0-255格式) carla_semantic_colors = np.array([ (0, 0, 0), # 0: Unlabeled (70, 70, 70), # 1: Building (100, 40, 40), # 2: Fence (55, 90, 80), # 3: Other (220, 20, 60), # 4: Pedestrian (153, 153, 153), # 5: Pole (157, 234, 50), # 6: Road line (128, 64, 128), # 7: Road (244, 35, 232), # 8: Sidewalk (107, 142, 35), # 9: Vegetation (0, 0, 142), # 10: Car (102, 102, 156), # 11: Wall (220, 220, 0), # 12: Traffic sign (70, 130, 180), # 13: Sky (81, 0, 81), # 14: Ground (150, 100, 100), # 15: Bridge (230, 150, 140), # 16: Rail track (180, 165, 180), # 17: Guard rail (250, 170, 30), # 18: Traffic light (110, 190, 160), # 19: Static (170, 120, 50), # 20: Dynamic (45, 60, 150), # 21: Water (145, 170, 100) # 22: Terrain ], dtype=np.uint8) # 输入语义mask,形状为[H, W],值为0-22的整数 semantic_mask = np.random.randint(0, 23, size=(200, 200), dtype=np.uint8) # 直接索引映射得到RGB图像,形状为[H, W, 3] rgb_mask = carla_semantic_colors[semantic_mask] # OpenCV展示示例(需要把RGB转BGR) cv2.imshow('semantic mask', cv2.cvtColor(rgb_mask, cv2.COLOR_RGB2BGR)) cv2.waitKey(0)
内容的提问来源于stack exchange,提问作者paul
相关产品推荐
相关产品推荐

