将灰度图像转换为RGB,反之亦然

2024-06-24 13:24:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个代码来转换地面真相灰度掩模RGB,反之亦然,但RGB2Grayscales不按预期工作?
标签和转换RGB的示例
label_image
Color_image

from __future__ import print_function, absolute_import, division
from collections import namedtuple
import numpy as np
import cv2

Label = namedtuple('Label',
                   ['name', 'id', 'trainId', 'category', 'categoryId', 'hasInstances', 'ignoreInEval', 'color', ])

labels = [
    #       name                     id    trainId   category            catId     hasInstances   ignoreInEval   color
    Label('unlabeled', 0, 19, 'void', 0, False, True, (0, 0, 0)),
    Label('ego vehicle', 1, 19, 'void', 0, False, True, (0, 0, 0)),
    Label('rectification border', 2, 19, 'void', 0, False, True, (0, 0, 0)),
    Label('out of roi', 3, 19, 'void', 0, False, True, (0, 0, 0)),
    Label('static', 4, 19, 'void', 0, False, True, (0, 0, 0)),
    Label('dynamic', 5, 19, 'void', 0, False, True, (111, 74, 0)),
    Label('ground', 6, 19, 'void', 0, False, True, (81, 0, 81)),
    Label('road', 7, 0, 'flat', 1, False, False, (128, 64, 128)),
    Label('sidewalk', 8, 1, 'flat', 1, False, False, (244, 35, 232)),
    Label('parking', 9, 19, 'flat', 1, False, True, (250, 170, 160)),
    Label('rail track', 10, 19, 'flat', 1, False, True, (230, 150, 140)),
    Label('building', 11, 2, 'construction', 2, False, False, (70, 70, 70)),
    Label('wall', 12, 3, 'construction', 2, False, False, (102, 102, 156)),
    Label('fence', 13, 4, 'construction', 2, False, False, (190, 153, 153)),
    Label('guard rail', 14, 19, 'construction', 2, False, True, (180, 165, 180)),
    Label('bridge', 15, 19, 'construction', 2, False, True, (150, 100, 100)),
    Label('tunnel', 16, 19, 'construction', 2, False, True, (150, 120, 90)),
    Label('pole', 17, 5, 'object', 3, False, False, (153, 153, 153)),
    Label('polegroup', 18, 19, 'object', 3, False, True, (153, 153, 153)),
    Label('traffic light', 19, 6, 'object', 3, False, False, (250, 170, 30)),
    Label('traffic sign', 20, 7, 'object', 3, False, False, (220, 220, 0)),
    Label('vegetation', 21, 8, 'nature', 4, False, False, (107, 142, 35)),
    Label('terrain', 22, 9, 'nature', 4, False, False, (152, 251, 152)),
    Label('sky', 23, 10, 'sky', 5, False, False, (70, 130, 180)),
    Label('person', 24, 11, 'human', 6, True, False, (220, 20, 60)),
    Label('rider', 25, 12, 'human', 6, True, False, (255, 0, 0)),
    Label('car', 26, 13, 'vehicle', 7, True, False, (0, 0, 142)),
    Label('truck', 27, 14, 'vehicle', 7, True, False, (0, 0, 70)),
    Label('bus', 28, 15, 'vehicle', 7, True, False, (0, 60, 100)),
    Label('caravan', 29, 19, 'vehicle', 7, True, True, (0, 0, 90)),
    Label('trailer', 30, 19, 'vehicle', 7, True, True, (0, 0, 110)),
    Label('train', 31, 16, 'vehicle', 7, True, False, (0, 80, 100)),
    Label('motorcycle', 32, 17, 'vehicle', 7, True, False, (0, 0, 230)),
    Label('bicycle', 33, 18, 'vehicle', 7, True, False, (119, 11, 32)),
    Label('license plate', -1, -1, 'vehicle', 7, False, True, (0, 0, 142)),
]


def trainIdToColor(trainId: int):
    for l in labels:
        if l.trainId == trainId:
            color = l.color
            break
    return color


def colortoTrainId(rgbColor):
    trainId = 0
    for l in labels:
        if l.color == rgbColor:
            trainId = l.trainId
            break
    return trainId


def gray2color(grayImage:np.ndarray,num_class:int):
    rgbImage=np.zeros((grayImage.shape[0],grayImage.shape[1],3),dtype='uint8')
    for cls in range(num_class):
        row,col=np.where(grayImage==cls)
        if (len(row)==0):
            continue
        color=trainIdToColor(cls)
        rgbImage[row,col]=color
    return rgbImage


def color2gray(colorImage:np.ndarray, bgr_color_space:bool):
    if bgr_color_space:
        colorImage = cv2.cvtColor(colorImage, cv2.COLOR_BGR2RGB)


    unique_color=np.unique(colorImage.reshape(-1, colorImage.shape[2]), axis=0)
    gray=np.zeros((colorImage.shape[0],colorImage.shape[1]),dtype=np.float32)
    for uc in unique_color:

        where_cond1= np.logical_and(colorImage[:,:,0]==uc[0],
                                    colorImage[:,:,1]==uc[1],
                                    colorImage[:,:,2]==uc[2])
        row,col=np.where(where_cond1)
        gray[row,col]=colortoTrainId(tuple(uc))

    return gray

当我使用灰度2色时,一切都很好。但是,当我尝试通过color2gray转换RGB图像时,它会转换,但结果与原始灰度图像不同。(将19秒改为13秒,其他课程可以)。我多次检查代码,但不知道为什么结果不好。
澄清
正如您在返回的灰度中所看到的,没有19值,所有值加起来都是13

original grayscale:
unique: 0   1   2   4   5   7   8   10  11  13  19
count:  624649  168701  819940  2802    24885   12192   42082   37098   6791    115270  242742

returned grayscale:
unique: 0   1   2   4   5   7   8   10  11  13
count:  624649  168701  819940  2802    24885   12192   42082   37098   6791    358012


另外,color2gray功能非常慢且耗时!你知道吗


Tags: importfalsetruenplabelcolorrowunique
2条回答

你的trainId值太低,所以你的灰度图像很暗。增加标签列表中trainId的值,并使您的灰度图像数据类型为uint8

def color2gray(colorImage:np.ndarray, bgr_color_space:bool):
    if bgr_color_space:
        colorImage = cv2.cvtColor(colorImage, cv2.COLOR_BGR2RGB)


    gray=np.zeros((colorImage.shape[0],colorImage.shape[1]),dtype=np.uint8)

    for row in range(colorImage.shape[0]):
        for col in range(colorImage.shape[1]):
            # either multiply the result of colortoTrainId(tuple(uc)) with some number
            # or change the value of trainId in the Labels list
            gray[row,col]=colortoTrainId(tuple(colorImage[row,col]))*10

    return gray

我自己找到了一个问题的答案

np.logical_and()只需要两个数组

所以必须这样嵌套使用

where_cond1=np.logical_and(np.logical_and(colorImage[:,:,0]==uc[0],colorImage[:,:,1]==uc[1]), colorImage[:,:,2]==uc[2])

但速度问题仍然存在,你知道如何矢量化分配吗?你知道吗

相关问题 更多 >