• 语义分割——灰度图像转伪彩色图像


    检验灰度图

    制作语义分割数据集或用训练好模型测试图像时,得到的结果是灰度图像,如下:
    在这里插入图片描述

    检验代码

    上面图像灰度值不是全是全为0,灰度范围在[0,1]之间,使用下面脚本测试灰度图像的灰度值是否全为0:

    import cv2
    
    img = cv2.imread("output/result/Result_2023.9.18_Int8/Val_Predict/BlockImage/1.png")
    
    min_val = img.min()
    max_val= img.max()
    
    print("min_val",min_val)
    print("max_val",max_val)
    print("dtype",img.dtype)
    print("shape",img.shape)
    print("img = ",img)
    
    cv2.imshow("1",img)
    cv2.waitKey()
    cv2.destroyWindow()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    通过上面脚本检测结果如下:

    在这里插入图片描述

    灰度图转伪彩色图代码

    上面的灰度图直观的看不了测试结果怎样,得将[0,1]区间的灰度值映射到[0,255],详解代码见下:

    from __future__ import print_function
    
    import argparse
    import os
    import os.path as osp
    import sys
    import numpy as np
    from PIL import Image
    
    
    def parse_args():
        parser = argparse.ArgumentParser(
            formatter_class=argparse.ArgumentDefaultsHelpFormatter)
        parser.add_argument(
            'dir_or_file', help='input gray label directory or file list path')
        parser.add_argument('output_dir', help='output colorful label directory')
        parser.add_argument('--dataset_dir', help='dataset directory')
        parser.add_argument('--file_separator', help='file list separator')
        return parser.parse_args()
    
    
    def get_color_map_list(num_classes):
        """
        Returns the color map for visualizing the segmentation mask,
        which can support arbitrary number of classes.
        Args:
            num_classes (int): Number of classes.
        Returns:
            (list). The color map.
        """
    
        num_classes += 1
        color_map = num_classes * [0, 0, 0]
        for i in range(0, num_classes):
            j = 0
            lab = i
            while lab:
                color_map[i * 3] |= (((lab >> 0) & 1) << (7 - j))
                color_map[i * 3 + 1] |= (((lab >> 1) & 1) << (7 - j))
                color_map[i * 3 + 2] |= (((lab >> 2) & 1) << (7 - j))
                j += 1
                lab >>= 3
        color_map = color_map[3:]
        return color_map
    
    
    def gray2pseudo_color(args):
        """将灰度标注图片转换为伪彩色图片"""
        input = args.dir_or_file
        output_dir = args.output_dir
        if not osp.exists(output_dir):
            os.makedirs(output_dir)
            print('Creating colorful label directory:', output_dir)
    
        color_map = get_color_map_list(256)
        if os.path.isdir(input):
            for fpath, dirs, fs in os.walk(input):
                for f in fs:
                    try:
                        grt_path = osp.join(fpath, f)
                        _output_dir = fpath.replace(input, '')
                        _output_dir = _output_dir.lstrip(os.path.sep)
    
                        im = Image.open(grt_path)
                        lbl = np.asarray(im)
    
                        lbl_pil = Image.fromarray(lbl.astype(np.uint8), mode='P')
                        lbl_pil.putpalette(color_map)
    
                        real_dir = osp.join(output_dir, _output_dir)
                        if not osp.exists(real_dir):
                            os.makedirs(real_dir)
                        new_grt_path = osp.join(real_dir, f)
    
                        lbl_pil.save(new_grt_path)
                        print('New label path:', new_grt_path)
                    except:
                        continue
        elif os.path.isfile(input):
            if args.dataset_dir is None or args.file_separator is None:
                print('No dataset_dir or file_separator input!')
                sys.exit()
            with open(input) as f:
                for line in f:
                    parts = line.strip().split(args.file_separator)
                    grt_name = parts[1]
                    grt_path = os.path.join(args.dataset_dir, grt_name)
    
                    im = Image.open(grt_path)
                    lbl = np.asarray(im)
    
                    lbl_pil = Image.fromarray(lbl.astype(np.uint8), mode='P')
                    lbl_pil.putpalette(color_map)
    
                    grt_dir, _ = osp.split(grt_name)
                    new_dir = osp.join(output_dir, grt_dir)
                    if not osp.exists(new_dir):
                        os.makedirs(new_dir)
                    new_grt_path = osp.join(output_dir, grt_name)
    
                    lbl_pil.save(new_grt_path)
                    print('New label path:', new_grt_path)
        else:
            print('It\'s neither a dir nor a file')
    
    
    if __name__ == '__main__':
        args = parse_args()
        gray2pseudo_color(args)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109

    转换代码使用细则

    使用该代码,只需要在终端去到该文件所在路径下,添加灰度图像文件夹路径和转换后的保存路径即可。

    终端中输入的命令为:

    python gray2pseudo_color.py <dir_or_file> <output_dir>
    
    • 1

    上面命令中:

    dir_or_file为灰度图所在的路径

    output_dir为转换后伪彩色图像的保存路径

    具体的使用方法见下图:

    在这里插入图片描述

    示例转换结果

    转换后的对比结果如下图:

    在这里插入图片描述

    总结

    以上就是语义分割中灰度图像转伪彩色图像的方法,希望能帮到你,多多支持,谢谢!

  • 相关阅读:
    汽车EDI:德国大众 EDI 项目案例
    026-从零搭建微服务-文件服务(二)
    【Linux】环境基础开发工具使用(万字汇总)
    mescroll 在uni-app 运行的下拉刷新和上拉加载的组件
    Linux中Too many open files
    uniapp h5实现Excel、Word、PDF文件在线预览,而不是跳转下载,也不需要下载
    阿里巴巴整理MySQL面试必问,“脱颖而出”征服面试官
    MySQL 开启远程连接
    C++ //练习 14.49 为上一题提到的类定义一个转换目标是bool的类型转换运算符,先不用在意这么做是否应该。
    uni-app对request封装(兼容java若依框架)
  • 原文地址:https://blog.csdn.net/qq_40280673/article/details/133087461