Use Python and OpenCV to batch visualize labelme segmentation annotation results

[Original Statement]
This article is an original article by the blogger and may not be reproduced without the blogger's permission.
For more algorithm summaries, please follow my blog: https://blog.csdn.net/suiyingy.

        In the field of computer vision, image segmentation is an important task, which can segment different objects or areas in the image at the pixel level. In the image segmentation task, manual annotation of data is a very critical link. This article will introduce how to use Python and OpenCV libraries to perform batch visualization of labelme segmentation annotation results.

1. Preparation

        Before starting, we need to install the following dependent libraries:
        - OpenCV: for image processing and visualization.
        - numpy: for array operations and color mapping.
        - glob: used for file path matching.
        - tqdm: used to display progress bar.
        - pathlib: used to handle file paths.

2. Single image segmentation and labeling visualization

        First, we need to define several auxiliary functions. Among them, the `cv_imread()` function is used to read image files and supports Chinese paths; the `single_sample_process()` function is used to process the segmentation and labeling results of a single image, and can choose to save an independent mask or a mixed display of the image and mask.

3. Batch image segmentation and labeling visualization

        Next, we can define the `batch_samples_process()` function to batch process all the images in the annotation folder. This function will traverse each annotation file, call the `single_sample_process()` function for processing, and save the results to the specified directory.

4. Category and color mapping

        In the program, we use the `classes` list to define the category names, and then map each category to the corresponding color through the `colmaps` dictionary. You can choose different methods to generate color maps, such as random colors, same colors, or specified colors.

5. Example and running

        Finally, we provide an example showing how to use the above functions to process labelme segmentation annotation results. You need to set the path to the annotation folder, the folder path to save the results, the image format, and the list of categories to be processed.

# -*- coding: utf-8 -*-
'''
labelme分割标注结果批量可视化显示与保存。
更多算法总结请关注博客:https://blog.csdn.net/suiyingy。
'''

import os
import cv2
import json
import numpy as np
from glob import glob
from tqdm import tqdm
from pathlib import Path


# 读取图片,支持中文路径
# file_path:图片文件路径
# 输出默认为BGR格式彩色图像矩阵
def cv_imread(file_path, flags=cv2.IMREAD_COLOR):
    cv_img=cv2.imdecode(np.fromfile(file_path, dtype=np.uint8), flags=flags)
    return cv_img

# 单张图片分割标注可视化
# iamge_path:图片文件路径
# label_path:标注文件路径
# save_path:标注mask保存路径,支持保存独立mask或图像与mask混合显示
# colmaps:字典格式,不同类别对应的mask颜色
# target:列表格式,仅处理target种指定类别,如果列表为空,则处理全部类别
def single_sample_process(image_path, label_path, save_path, colmaps, target=[]):
    image   = cv_imread(image_path)
    h, w, _ = image.shape
    anns    = json.load(open(label_path, "r", encoding="utf-8"))
    mask    = np.zeros((h, w, 3), dtype=np.uint8)
    for shape in anns['shapes']:
        label = shape['label']
        if len(target) > 0 and label not in target: # 筛选指定标签
            continue
        points = np.array(shape['points'], np.int32)
        mask_tmp = np.zeros((h, w), dtype=np.uint8)
        cv2.fillPoly(mask_tmp, [points], 255)
        cv2.fillPoly(mask, [points], colmaps[label])
        image[mask_tmp > 0] = image[mask_tmp > 0] * 0.5  + np.array(colmaps[label]).astype(np.uint8) * 0.5
        cv2.polylines(image, [points], True, (0, 255, 0), 3)
        cx, cy = ((np.min(points, 0)) + (np.max(points, 0))) // 2 - 20
        cv2.putText(image, label, (cx, cy), cv2.FONT_HERSHEY_COMPLEX, 2, (0, 0, 0))
        cv2.imwrite(save_path, mask)
    # 可视化
    # cv2.namedWindow('maskimg', 0)
    # cv2.imshow('maskimg', image)
    # cv2.waitKey(0)
    # cv2.namedWindow('mask', 0)
    # cv2.imshow('mask', mask)
    # cv2.waitKey(0)

# 批量图片分割标注可视化
# root_dir:标注文件的文件夹目录
# colmaps:字典格式,不同类别对应的mask颜色
# save_dir:标注mask的保存文件夹目录,支持保存独立mask或图像与mask混合显示
# img_type:原始图片格式
# target:列表格式,仅处理target种指定类别,如果列表为空,则处理全部类别
def batch_samples_process(root_dir, colomaps, save_dir='res', img_type='png', target=[]):
    root_dir = str(Path(root_dir)) + '/'
    save_dir = str(Path(save_dir)) + '/'
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
    label_files = glob(root_dir + '*.json')
    for label_path in tqdm(label_files):
        filename = os.path.basename(label_path)
        image_path = label_path.replace('.json', '.' + img_type)
        save_path = save_dir + filename + '.png'
        single_sample_process(image_path, label_path, save_path, colomaps, target)
        # break

if __name__ == '__main__':
    # 类别
    classes = ['aa', 'bb', 'cc']
    # 类别与与MASK对应的颜色,下面三种方法可任意选择一种
    colmaps = dict(zip(classes, np.random.randint(0, 256, (1, 3), dtype=np.uint8).tolist() * len(classes)))#初始化成相同颜色
    colmaps = dict(zip(classes, np.random.randint(0, 256, (len(classes), 3), dtype=np.uint8).tolist()))#初始化成随机颜色
    colmaps = {'aa': [255, 0, 0], 'bb': [0, 255, 0], 'cc': [0, 0, 255]}#初始化成指定颜色
    root_dir = r'D:\aaa'
    save_dir = r'res'
    image_files = os.listdir(root_dir)
    batch_samples_process(root_dir, colmaps, save_dir, 'png', ['aa', 'bb', 'cc'])

        This article introduces the method of batch visualization of labelme segmentation annotation results using Python and OpenCV. By defining several auxiliary functions and main functions, we can easily read the images and annotation data in the annotation folder, and save the results as independent mask files or display mixed images and masks. This visual processing method can help us understand the segmentation annotation results more intuitively and be used for further image analysis and deep learning model training.

        If you are interested in this method, you can click [here](https://blog.csdn.net/suiyingy) to view more relevant algorithm summaries and practical experiences .

[Original Statement]
This article is an original article by the blogger and may not be reproduced without the blogger's permission.
For more algorithm summaries, please follow my blog: https://blog.csdn.net/suiyingy.

Guess you like

Origin blog.csdn.net/suiyingy/article/details/133273773