Python OpenCV图像标注转换为掩码图像代码详解
这段代码使用 Python OpenCV 库,将标注好的图像转换为对应的掩码图像。
首先,通过读取文件夹中的所有图像,循环遍历其中的每张图像。
然后,读取与该图像对应的 JSON 文件,该文件中保存了该图像的标注信息。利用 Python 自带的 json 库,将 JSON 文件中的信息读取为一个 Python 字典类型的变量 'label'。
接着,从 'label' 变量中取出该图像标注的所有形状信息,即 'shapes' 变量。
对于每个形状,首先获取其标注的类别 'category' 和点集 'points'。将点集转换为 NumPy 数组 'points_array',并利用 OpenCV 库中的 'fillPoly' 函数将该形状对应的掩码图像 'mask' 中对应区域填充为 255。
最后,将生成的掩码图像 'mask' 保存到指定的文件夹中,文件名与原始图像文件名相同。
代码示例:
import cv2
import numpy as np
import json
import os
json_path = "/grinding_wheel/json/"
img_path = "/grinding_wheel/images/"
mask_path = "/grinding_wheel/mask_path/"
images = os.listdir(img_path)
for i in images:
img = cv2.imread(img_path+i)
h, w = img.shape[:2]
mask = np.zeros([h, w, 1], np.uint8)
with open(json_path+i[:-4]+'.json',"r") as f:
label = json.load(f)
shapes = label['shapes']
for shape in shapes:
category = shape['label']
points = shape['points']
points_array = np.array(points, dtype=np.int32)
mask = cv2.fillPoly(mask, [points_array], 255)
# mask = cv2.fillPoly(mask, [points_array], category_types.index(category))
cv2.imwrite(mask_path+i, mask)
代码解释:
cv2.imread(img_path+i): 读取图像文件np.zeros([h, w, 1], np.uint8): 创建一个与图像大小相同的掩码图像,初始值全部为0json.load(f): 读取JSON文件中的标注信息cv2.fillPoly(mask, [points_array], 255): 将形状对应的区域填充为255cv2.imwrite(mask_path+i, mask): 保存生成的掩码图像
总结:
这段代码使用 Python OpenCV 库,将标注好的图像转换为对应的掩码图像。通过读取 JSON 文件中的标注信息,并利用 fillPoly 函数将形状对应的区域填充为 255,生成掩码图像。该代码可以用于多种图像处理任务,例如图像分割、目标检测等。
原文地址: https://www.cveoy.top/t/topic/oMPC 著作权归作者所有。请勿转载和采集!