#image掩膜图像 掩膜图像下的真实图片
import json
import numpy as np
import cv2
import os
from glob import glob
# Define input directory for JSON files
json_dir = "test/json/"#json文件,里面有json文件相应的image文件
# Define output directory for masks
output_dir = "masks"#掩膜文件路径,是0或者255
output_dir1 = "roi/"#掩膜文件夹的原图
os.makedirs(output_dir, exist_ok=True)
# Get list of JSON files
json_files = glob(os.path.join(json_dir, "*.json"))
# Iterate over each JSON file
for json_file in json_files:
# Extract filename without extension
filename = os.path.splitext(os.path.basename(json_file))[0]
# Read JSON file
with open(json_file, "r") as f:
data = json.load(f)
# Read corresponding image file
image_file = os.path.join(json_dir, filename + ".TIF") # Assuming image files are in JPG format
image = cv2.imread(image_file)
# Create a blank mask
mask = np.zeros_like(image, dtype=np.uint8)
# Iterate over shapes in JSON data
for shape in data["shapes"]:
points = np.array(shape["points"], dtype=np.int32)
cv2.fillPoly(mask, [points], (255, 255, 255))
region = mask == 0
image[region] = 0
# Save the mask
output_path = os.path.join(output_dir, f"mask_{filename}.TIF")
save_path = os.path.join(output_dir1, f"mask_{filename}.TIF")
cv2.imwrite(output_path, mask)#二值化图
cv2.imwrite(save_path, image)#掩膜图
print(f"Processed: {json_file}")
print("All JSON files processed successfully.")
json文件掩膜成黑白图片和根据掩膜图像来掩膜原图
于 2024-03-18 11:22:04 首次发布