语义分割批量 json文件手动可视化,设置指定颜色以及透明度

  1. 设置原始图片路径
  2. 设置json文件路径
  3. 设置保存文件路径
  4. 设置不同类别对应的颜色
  5. 设置透明度
  6. run
# -*- encoding: utf-8 -*-
# Author  : haitong
# Time    : 2023/5/25 15:32
# File    : JsonVisualization.py
# Software: PyCharm

import cv2
import numpy as np
from PIL import Image
import json
import os


def JsonVisualization(data_file_dir, json_file_dir, save_file_dir, bbox_color_dict, transparency):
    for img_name in os.listdir(data_file_dir):
        if img_name.endswith('.jpg') or img_name.endswith('.png'):
            print(img_name)
            img_path = os.path.join(data_file_dir, img_name)
            json_name = img_name[:-3] + "json"
            json_path = os.path.join(json_file_dir, json_name)

            # img_ori = cv2.imread(img_path)
            img_ori = Image.open(img_path)
            img_ori = cv2.cvtColor(np.asarray(img_ori), cv2.COLOR_RGB2BGR)
            zeros = np.zeros(img_ori.shape, dtype=np.uint8)

            with open(json_path) as fp:
                json_data = json.load(fp)

            for shape in json_data["shapes"]:
                label = shape['label']
                dot = shape['points']

                pts = np.array((np.array(dot)).reshape((-1, 1, 2)), np.int32)
                # cv2.polylines(img, [pts], True, (0, 0, 255), 0)
                mask = cv2.fillPoly(zeros, [pts], bbox_color_dict[label])

            img_save = cv2.addWeighted(img_ori, 1, mask, transparency, 0)  # 0.5 透明度

            # cv2.imwrite(os.path.join(save_file_dir, img_name), img)
            image = Image.fromarray(cv2.cvtColor(img_save, cv2.COLOR_BGR2RGB))
            image.save(os.path.join(save_file_dir, img_name))

    return 1

if __name__ == "__main__":
    dir_path = os.path.dirname(os.path.abspath(__file__))
    data_file_dir = os.path.join(dir_path, 'Image')  					   # 原始图片路径
    json_file_dir = os.path.join(dir_path, 'segmentation') 				   # json路径
    save_file_dir =  os.path.join(dir_path, 'Save')						   # 保存路径
    bbox_color_dict = {'breakage': (0, 0, 255), 'corrosion': (0, 255, 0)}  # 设置对应检测目标的颜色
    transparency = 0.5													   # 掩膜透明度
    _ = JsonVisualization(data_file_dir, json_file_dir, save_file_dir, bbox_color_dict, transparency)

你可能感兴趣的:(python,deep,learning,labelme,json标签可视化)