含mask的单通道灰度图内容可视化python

输入:单通道的灰度图,灰度图内含不同像素值的掩膜mask

输出:灰度图内的掩膜mask在RGB图像中输出

方法很简单,就是读取灰度图,根据掌握的像素值信息,分别赋予不同的颜色值像素进行保存输出。

如下输入的单通道灰度图:

使用如下代码处理:

python 复制代码
import os
import sys
import cv2
import numpy as np 



def main():
    mask_dir = './mask'
    show_dir = './mask_out'
    for mskf in os.listdir(mask_dir):
        msfile = mask_dir + '/' + mskf
        # msimg = cv2.imread(msfile, cv2.IMREAD_GRAYSCALE) 读出是单通道
       

        msimg = cv2.imread(msfile)
                
        # poly = mask2poly(msimg)
        """提供的mask的像素值是0,1,2,0是背景,现在在三通道图像中针对像素值赋予颜色像素"""
        # msimg[msimg==1]=255
        rms = msimg[:,:,0]
        gms = msimg[:,:,1]
        bms = msimg[:,:,2]

        #1-0,255,0
        rms[rms==1] = 0
        bms[bms==1] = 255
        gms[gms==1] = 0

        #2-0,0,255
        rms[rms==2] = 0
        bms[bms==2] = 0
        gms[gms==2] = 255

        showimg = show_dir + '/' + mskf

        cv2.imwrite(showimg,msimg)
        

if __name__ == '__main__':
    main()

输出结果如下:

相关推荐
zone773920 小时前
001:简单 RAG 入门
后端·python·面试
F_Quant21 小时前
🚀 Python打包踩坑指南:彻底解决 Nuitka --onefile 配置文件丢失与重启报错问题
python·操作系统
允许部分打工人先富起来1 天前
在node项目中执行python脚本
前端·python·node.js
IVEN_1 天前
Python OpenCV: RGB三色识别的最佳工程实践
python·opencv
haosend1 天前
AI时代,传统网络运维人员的转型指南
python·数据网络·网络自动化
曲幽1 天前
不止于JWT:用FastAPI的Depends实现细粒度权限控制
python·fastapi·web·jwt·rbac·permission·depends·abac
IVEN_2 天前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang2 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮2 天前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling2 天前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python