opencv如何保存索引图像(带调色板)

例如保存位深度为8的彩色图像,总共是256色。但是opencv似乎只提供8位灰度图,而且最低8位。

256色不就是8bit位深吗?png格式可以存成8位深的彩色图,如果你接触过VOC数据集就知道里面的mask就是这种格式的彩色图,不过opencv好像存不了这个格式的,一般都是用的PIL存的。扒一个labelme的源码

import os.path as osp

import numpy as np
import PIL.Image


def lblsave(filename, lbl):
    import imgviz
    if osp.splitext(filename)[1] != ".png":
        filename += ".png"
    # Assume label ranses [-1, 254] for int32,
    # and [0, 255] for uint8 as VOC.
    if lbl.min() >= -1 and lbl.max() < 255:
        lbl_pil = PIL.Image.fromarray(lbl.astype(np.uint8), mode="P")
        colormap = imgviz.label_colormap()
        lbl_pil.putpalette(colormap.flatten())
        lbl_pil.save(filename)
    else:
        raise ValueError(
            "[%s] Cannot save the pixel-wise class label as PNG. "
            "Please consider using the .npy format." % filename
        )