Python 将灰度图像转换为RGB,反之亦然
我写了一个代码,将地面真实灰度蒙版转换为RGB,反之亦然,但RGB2Grayscales不能按预期工作?Python 将灰度图像转换为RGB,反之亦然,python,numpy,image-processing,computer-vision,cv2,Python,Numpy,Image Processing,Computer Vision,Cv2,我写了一个代码,将地面真实灰度蒙版转换为RGB,反之亦然,但RGB2Grayscales不能按预期工作? 标签和转换RGB的示例 当我使用gray2color时,一切都很好。但是,当我尝试通过color2gray转换RGB图像时,它会转换,但结果与原始灰度图像不同(将19秒更改为13秒,其他类可以使用)。我多次检查代码,但不知道为什么结果不好。 澄清 正如您在返回的灰度中所看到的,没有19个值,所有值加起来都是13秒 original grayscale: unique: 0 1
标签和转换RGB的示例
当我使用gray2color时,一切都很好。但是,当我尝试通过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功能非常缓慢且耗时 您的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\u and()
只需要两个数组
所以它必须像这样嵌套使用
where_cond1=np.logical_and(np.logical_and(colorImage[:,:,0]==uc[0],colorImage[:,:,1]==uc[1]), colorImage[:,:,2]==uc[2])
但是速度问题仍然存在,知道如何矢量化分配吗?灰度图像不是用来显示的,它是NN输出的掩码。这不是我的问题,问题是当我查看返回的灰度矩阵时,任何19的值都被替换为13。这很奇怪,我也改变了答案。现在你会得到190(即19)的灰度图像,但当你在做像素级的操作时,这将是耗时的。在我的on代码中,这不是像素级的。同样的问题,你的代码是像素级的。查看这两行
row,col=np.where(where_cond1)
gray[row,col]=colortrainid(tuple(uc))
。您正在查找特定颜色所在的位置,然后在灰色图像中为这些位置赋值。您似乎已将灰色
设置为np.float32
?是的,这与我的问题有什么关系?(19被13取代)@marksetchell有人投了反对票,但问题就这样解决了
where_cond1=np.logical_and(np.logical_and(colorImage[:,:,0]==uc[0],colorImage[:,:,1]==uc[1]), colorImage[:,:,2]==uc[2])