按指定颜色给语义分割标签上色

import base64
import json
import os
import os.path as osp

import numpy as np
import PIL.Image
from labelme import utils


if __name__ == '__main__':
    pngs_path = "outputlabel"
    if not osp.exists(pngs_path):
        os.mkdir(pngs_path)
    classes = ["_background_", "person", "cat", "tv", "train", "bird", "boat", "airpline", "sheep"]
    color_map = {
        0: (0, 0, 0),  # _background_
        1: (255, 0, 0),  # person
        2: (0, 255, 0),  # cat
        3: (0, 0, 255),  # tv
        4: (255, 255, 0),  # train
        5: (255, 0, 255),  # bird
        6: (0, 255, 255),  # boat
        7: (128, 0, 0),  # airpline
        8: (0, 128, 0)  # sheep
    }

    count = os.listdir("label")
    for i in range(0, len(count)):
        path = os.path.join("label", count[i])

        if os.path.isfile(path) and path.endswith('json'):
          
计算机视觉和图像处理中,语义分割通常用于将图像中的每个像素分配到相应的类别。要在Python中,特别是使用深度学习库如PyTorch或TensorFlow,我们可以使用预训练的语义分割模型并对其进行可视化。这里是一个简单的例子,展示如何使用Segmentation Models库进行预测并上色: ```python import torch from PIL import Image import segmentation_models_pytorch as smp # 加载预训练模型 model = smp.Unet('resnet50', classes=21) # 使用ResNet50作为基础模型,假设我们有21个类别 model.load_state_dict(torch.load('your_model.pth')) # 替换为实际模型路径 # 预测前准备一张图片 image_path = 'path_to_your_image.jpg' img = Image.open(image_path) img = img.resize((model.input_size[1], model.input_size[0])) # 确保输入尺寸匹配模型期望 # 将图片转换为张量并标准化 tensor_img = smp.utils.image.to_tensor(img).unsqueeze(0) seg_map = model(tensor_img) # 获取概率最大的类别,并将其转换回原图尺寸 _, preds = torch.max(seg_map, dim=1) preds = preds.squeeze().cpu().numpy() preds = np.argmax(preds, axis=-1) # 对分割结果进行颜色编码 color_palette = smp.utils.color_palette('cityscapes')[:classes] # 假设我们还是21类 colored_img = Image.fromarray(preds.astype(np.uint8)).apply_color_pallete(color_palette) # 显示原图和上色后的结果 colored_img.show() ``` 请注意,你需要替换`your_model.pth`为你实际保存的模型文件路径,以及根据需要调整类别数、颜色编码等。这个代码展示了基本的概念,实际应用可能需要更复杂的图像预处理和后处理步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值