OpenCV的label2rgb实现

时间:2019-07-17 04:07:32

标签: python matlab opencv

OpenCV是否具有可以可视化标签Mat的功能?即,类似的Matlab label2rgb()

我能找到的最接近的是:cv2.applyColorMap(cv2.equalizeHist(segments), cv2.COLORMAP_JET)

但是,在分割标签数量从一帧变为下一帧的视频分割时,这不是一种理想的方法。原因是;一帧将有2个标签(0和1-分别代表天空和地面),因此使用jet可能会将这2个分段分别显示为深蓝色和红色。下一个帧具有3个标签(0,1,2-天空,地面和汽车),因此地面部分现在已从红色变为黄色。因此,当您对此进行可视化时,相同的细分会不断改变颜色,而不会保持一致的颜色(红色)。

因此,如果存在像matlabs label2rbg()这样的函数真的有用吗?

1 个答案:

答案 0 :(得分:3)

我喜欢将cv2.LUT用于少于256个标签(因为它仅适用于uint8)。如果标签超过256个,则始终可以使用(labels % 256).astype(np.uint8)转换为256个值。

然后用您的标签简单地调用:rgb = cv2.LUT(labels, lut)

唯一剩下的问题是为标签创建查找表(lut)。您可以按如下方式使用matplotlib颜色图:

import numpy as np
import matplotlib.pyplot as plt
import cv2

def label2rgb(labels):
  """
  Convert a labels image to an rgb image using a matplotlib colormap
  """
  label_range = np.linspace(0, 1, 256)
  lut = np.uint8(plt.cm.viridis(label_range)[:,2::-1]*256).reshape(256, 1, 3) # replace viridis with a matplotlib colormap of your choice
  return cv2.LUT(cv2.merge((labels, labels, labels)), lut)

在许多情况下,最好使相邻标签的颜色有很大的不同。 Rick Szelski在其book的附录C2:伪彩色生成中给出了伪代码来实现此目的。过去我一直在研究他的算法及其变体,编写某些代码非常简单。这是使用他的算法的示例代码:

import numpy as np
import cv2


def gen_lut():
  """
  Generate a label colormap compatible with opencv lookup table, based on
  Rick Szelski algorithm in `Computer Vision: Algorithms and Applications`,
  appendix C2 `Pseudocolor Generation`.
  :Returns:
    color_lut : opencv compatible color lookup table
  """
  tobits = lambda x, o: np.array(list(np.binary_repr(x, 24)[o::-3]), np.uint8)
  arr = np.arange(256)
  r = np.concatenate([np.packbits(tobits(x, -3)) for x in arr])
  g = np.concatenate([np.packbits(tobits(x, -2)) for x in arr])
  b = np.concatenate([np.packbits(tobits(x, -1)) for x in arr])
  return np.concatenate([[[b]], [[g]], [[r]]]).T

def labels2rgb(labels, lut):
  """
  Convert a label image to an rgb image using a lookup table
  :Parameters:
    labels : an image of type np.uint8 2D array
    lut : a lookup table of shape (256, 3) and type np.uint8
  :Returns:
    colorized_labels : a colorized label image
  """
  return cv2.LUT(cv2.merge((labels, labels, labels)), lut)

if __name__ == '__main__':
  labels = np.arange(256).astype(np.uint8)[np.newaxis, :]
  lut = gen_lut()
  rgb = labels2rgb(labels, lut)

这是颜色图:

enter image description here

相关问题