用深度学习算法对图像进行分割任务后,得到的分割图像中的物体往往是各种不同深浅的灰色,不容易看清楚各物体的界限。以VOC2012为例,可以使用以下程序对分割后输出的图像批量修改颜色。
import os
from PIL import Image
import time
from tqdm import tqdm
# 源目录
MyPath = 'D:\code\ChangeColor\sem_seg/'
# 输出目录
OutPath = 'D:\code\ChangeColor\sem_seg_out/'
def processImage(filesoure, destsoure, name, imgtype):
'''
filesoure是存放待转换图片的目录
destsoure是存在输出转换后图片的目录
name是文件名
imgtype是文件类型
'''
imgtype = 'bmp' if imgtype == '.bmp' else 'png'
# 打开图片
im = Image.open(filesoure + name)
img = im.convert("RGBA")
pixdata = img.load()
# 二值化
for y in range(img.size[1]):
for x in range(img.size[0]):
if pixdata[x, y][0] ==1:
pixdata[x, y] = (128,0,0, 255)
if pixdata[x, y][0] ==2:
pixdata[x, y] = (0,128,0, 255)
if pixdata[x, y][0] ==3:
pixdata[x, y] = (128,128,0, 255)
if pixdata[x, y][0] ==4:
pixdata[x, y] = (0, 0, 128, 255)
if pixdata[x, y][0] ==5:
pixdata[x, y] = (128,0,128, 255)
if pixdata[x, y][0] ==6:
pixdata[x, y] = (0,128,128, 255)
if pixdata[x, y][0] ==7:
pixdata[x, y] = (128,128,128, 255)
if pixdata[x, y][0] ==8:
pixdata[x, y] = (64,0,0, 255)
if pixdata[x, y][0] ==9:
pixdata[x, y] = (192,0,0, 255)
if pixdata[x, y][0] ==10:
pixdata[x, y] = (64,128,0, 255)
if pixdata[x, y][0] ==11:
pixdata[x, y] = (192,128,0, 255)
if pixdata[x, y][0] ==12:
pixdata[x, y] = (64,0,128, 255)
if pixdata[x, y][0] ==13:
pixdata[x, y] = (192,0,128, 255)
if pixdata[x, y][0] ==14:
pixdata[x, y] = (64,128,128, 255)
if pixdata[x, y][0] ==15:
pixdata[x, y] = (192,128,128, 255)
if pixdata[x, y][0] ==16:
pixdata[x, y] = (0,64,0, 255)
if pixdata[x, y][0] ==17:
pixdata[x, y] = (128,64,0, 255)
if pixdata[x, y][0] ==18:
pixdata[x, y] = (0,192,0, 255)
if pixdata[x, y][0] ==19:
pixdata[x, y] = (128,192,0, 255)
if pixdata[x, y][0] ==20:
pixdata[x, y] = (0,64,128, 255)
# for y in range(img.size[1]):
# for x in range(img.size[0]):
# if pixdata[x, y][1] !=0:
# pixdata[x, y] = (255, 255, 255, 255)
#
# for y in range(img.size[1]):
# for x in range(img.size[0]):
# if pixdata[x, y][2] != 0:
# pixdata[x, y] = (255, 255, 255, 255)
img.save(destsoure + name, imgtype)
def run():
# 切换到源目录,遍历源目录下所有图片
os.chdir(MyPath)
for i in tqdm(os.listdir(os.getcwd())):
# 检查后缀
postfix = os.path.splitext(i)[1]
if postfix == '.bmp' or postfix == '.png':
processImage(MyPath, OutPath, i, postfix)
time.sleep(0.01)
if __name__ == '__main__':
run()
修改后的分割图像如图所示:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)