json文件掩膜成黑白图片和根据掩膜图像来掩膜原图

#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.")
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Python中的json和os模块来实现将json文件中的图片文件分开的功能。 假设你有一个名为data.jsonjson文件,其中包含了图片文件的路径和一些其他的信息,你可以按照以下步骤进行操作: 1. 读取json文件并加载数据: ```python import json with open('data.json', 'r') as f: data = json.load(f) ``` 2. 遍历数据,并将图片文件分离出来: ```python import os import shutil for item in data: if 'image_path' in item: image_path = item['image_path'] if os.path.exists(image_path): # 目标路径为当前目录下的image文件夹内 target_path = './image/' + os.path.basename(image_path) # 复制文件到目标路径 shutil.copy2(image_path, target_path) # 更新json数据中的图片路径为目标路径 item['image_path'] = target_path ``` 这段代码首先判断当前数据中是否包含图片路径,如果有的话则将图片文件复制到指定目录下的image文件夹内,然后更新json数据中的图片路径为目标路径。 注意,在运行上述代码之前,你需要确保当前目录下存在一个名为image的文件夹,以便存储分离出来的图片文件。 3. 将更新后的数据保存到json文件中: ```python with open('data.json', 'w') as f: json.dump(data, f) ``` 这段代码将更新后的数据保存到原始的json文件中,以便后续使用。 综上所述,你可以使用上述代码将json文件中的图片文件分离出来,并将更新后的数据保存到json文件中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值