FCN Image Segmentation | Data Preparation

Reference: How to label mask for image segmentation model training

1. Details of using the marking tool

Use VIA annotation tool

  1. remove sample image
    Insert picture description here

  2. add own picture
    Insert picture description here

  3. Set attributes according to different tasks. It is not necessary to
    purely segment an object. If you classify multiple objects, please inquire separately.
    Insert picture description here

  4. Draw contour
    Insert picture description here
    Note: You can press esc when you want to exit during drawing, press enter when you finish drawing, and click to select the contour to adjust the position of the node. For details, please refer to Help-Gettong Started.
    Insert picture description here

  5. Save
    -okInsert picture description here

2. Convert to mask

Run the following code:

import os
import json
import numpy as np
import skimage.draw
import cv2

IMAGE_FOLDER = "./train/"
MASK_FOLOER = "./mask/"
PATH_ANNOTATION_JSON = 'box.json'

# 加载VIA导出的json文件
annotations = json.load(open(PATH_ANNOTATION_JSON, 'r'))
imgs = annotations["_via_img_metadata"]

for imgId in imgs:
    filename = imgs[imgId]['filename']
    regions = imgs[imgId]['regions']
    if len(regions) <= 0:
        continue

    # 取出第一个标注的类别,本例只标注了一个物件
    polygons = regions[0]['shape_attributes']

    # 图片路径
    image_path = os.path.join(IMAGE_FOLDER, filename)
    # 读出图片,目的是获取到宽高信息
    image = cv2.imread(image_path)  # image = skimage.io.imread(image_path)
    height, width = image.shape[:2]

    # 创建空的mask
    maskImage = np.zeros((height,width), dtype=np.uint8)
    countOfPoints = len(polygons['all_points_x'])
    points = [None] * countOfPoints
    for i in range(countOfPoints):
        x = int(polygons['all_points_x'][i])
        y = int(polygons['all_points_y'][i])
        points[i] = (x, y)

    contours = np.array(points)

    # 遍历图片所有坐标
    for i in range(width):
        for j in range(height):
            if cv2.pointPolygonTest(contours, (i, j), False) > 0:
                maskImage[j,i] = 1

    savePath = MASK_FOLOER + filename
    # 保存mask
    cv2.imwrite(savePath, maskImage)

Guess you like

Origin blog.csdn.net/weixin_42326479/article/details/107185379