CV图像处理小工具——json文件转mask
import cv2
import json
import numpy as np
import os
def func(file_path: str) -> np.ndarray:
try:
with open(file_path, mode='r', encoding="utf-8") as f:
configs = json.load(f)
# 检查JSON是否包含必要的字段
if "shapes" not in configs or "imageHeight" not in configs or "imageWidth" not in configs:
raise ValueError("JSON文件缺少必要的字段")
shapes = configs["shapes"]
image_height = configs["imageHeight"]
image_width = configs["imageWidth"]
png = np.zeros((image_height, image_width, 3), np.uint8)
for shape in shapes:
if "points" not in shape:
raise ValueError("形状缺少点信息")
points = np.array(shape["points"], np.int32).reshape((-1, 1, 2)) # 确保点是正确的形状
cv2.fillPoly(png, [points], (0, 0, 255))
return png
except Exception as e:
print(f"处理文件 {file_path} 时出错: {e}")
return None
# 硬编码的文件路径
input_directory = "H:/" # 可以是单个文件路径或目录路径
output_directory = "H:/"
# 确保输出目录存在
if not os.path.exists(output_directory):
os.makedirs(output_directory)
# 处理单个文件或目录中的文件
if os.path.isfile(input_directory) and input_directory.endswith(".json"):
# 处理单个JSON文件
input_file = input_directory
output_file = os.path.join(output_directory, os.path.splitext(os.path.basename(input_file))[0] + ".png")
image = func(input_file)
if image is not None:
cv2.imwrite(output_file, image)
else:
# 处理目录中的JSON文件
for file_name in os.listdir(input_directory):
if file_name.endswith(".json"):
input_file = os.path.join(input_directory, file_name)
output_file = os.path.join(output_directory, os.path.splitext(file_name)[0] + ".png")
image = func(input_file)
if image is not None:
cv2.imwrite(output_file, image)