转化后的数据
mask
叠加到影像上
代码
import os
import glob
from labelme import utils
import numpy as np
from labelme.utils import image
import argparse
import json
import matplotlib.pyplot as plt
import cv2
import gdalTools
if __name__ == '__main__':
labellist = glob.glob('D:/2021/7/3dReconstruction/label/*.json')
imgRoot = 'D:/2021/7/3dReconstruction/data0719_2'
outdir = 'D:/2021/7/3dReconstruction/mask'
gdalTools.mkdir(outdir)
for labelPath in labellist:
baseName = os.path.basename(labelPath).split('.')[0]
imgPath = glob.glob(f'{imgRoot}/{baseName}.jpg')[0]
img = cv2.imread(imgPath)
data = json.load(open(labelPath)) # 加载json文件
lbl, lbl_names = utils.labelme_shapes_to_label(img.shape, data['shapes'])
mask = []
class_id = []
for i in range(1, len(lbl_names)): # 跳过第一个class(因为0默认为背景,跳过不取!)
mask.append((lbl == i).astype(np.uint8)) # 举例:当解析出像素值为1,此时对应第一个mask 为0、1组成的(0为背景,1为对象)
class_id.append(i) # mask与class_id 对应记录保存
mask = np.asarray(mask).squeeze().astype(np.uint8)
w, h = mask.shape
mask2 = np.zeros((w, h, 3)).astype(np.uint8)
mask2[:, :, 0] = mask * 255
mask2[:, :, 1] = 0
mask2[:, :, 2] = mask * 255
img_out = np.zeros((w, h, 3)).astype(np.uint8)
img_out[:, :, 0] = np.where(mask > 0, img[:, :, 0] * 0.4 + mask2[:, :, 0] * 0.6, img[:, :, 0])
img_out[:, :, 1] = np.where(mask > 0, img[:, :, 1] * 0.4 + mask2[:, :, 1] * 0.6, img[:, :, 1])
img_out[:, :, 2] = np.where(mask > 0, img[:, :, 2] * 0.4 + mask2[:, :, 2] * 0.6, img[:, :, 2])
img_out = img_out.astype(np.uint8)
outName = os.path.join(outdir, f'{baseName}.jpg')
# cv2.imwrite(outName, img_out)
plt.imshow(img_out)
plt.show()