天天看點

json2mask等檔案

轉化後的資料

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()