binary segmentation 数据处理脚本小结

1.首先是json2image,废话少说,看代码

import base64
import json
import os
import os.path as osp
import uuid

import imgviz
import PIL.Image
from labelme import utils

if __name__ == "__main__":

    base_dir = osp.dirname(osp.abspath(__file__))
#输出图像与mask路径
    out_dir_name = "output"
    out_dir = osp.join(base_dir, out_dir_name)
    if not osp.exists(out_dir):
        os.mkdir(out_dir)
    label_names = []
    label_file = "./label.txt"
    label_value_dict = {}
    with open(label_file) as f:
        labels = f.readlines()
        if len(labels) > 0:
            for i, item in enumerate(labels):
                item = item.strip()
                label_value_dict[item] = i
#json输入标签
    json_file_name = "json"  #'cityspaces'
    json_file_path = osp.join(base_dir, json_file_name)
    #第一张图从几开始
    new_filename = 1095
    for file_name in os.listdir(json_file_path):
        print(file_name)
        if file_name.endswith(".json"):
            filePath = osp.join(json_file_path, file_name)
            data = json.load(open(filePath))
            imageData = data.get("imageData")
            if not imageData:
                imagePath = os.path.join(os.path.dirname(filePath),
                                         data["imagePath"])
                with open(imagePath, "rb") as f:
                    imageData = f.read()
                    imageData = base64.b64encode(imageData).decode("utf-8")

            img = utils.img_b64_to_arr(imageData)

            for shape in sorted(data["shapes"], key=lambda x: x["label"]):
                label_name = shape["label"]
                if label_name not in label_value_dict:
                    label_value = len(label_value_dict)
                    label_value_dict[label_name] = label_value

            lbl, _ = utils.shapes_to_label(img.shape, data["shapes"],
                                           label_value_dict)

            label_names = [None] * (max(label_value_dict.values()) + 1)
            for name, value in label_value_dict.items():
                label_names[value] = name

            lbl_viz = imgviz.label2rgb(lbl,
                                       imgviz.asgray(img),
                                       label_names=label_names,
                                       loc="rb")

            #new_filename = uuid.uuid4().hex

            PIL.Image.fromarray(img).save(
                osp.join(out_dir,
                         str(new_filename) + ".jpg"))
            utils.lblsave(
                osp.join(out_dir,
                         str(new_filename)+ ".png"), lbl)
            new_filename = new_filename + 1
            #PIL.Image.fromarray(lbl_viz).save(
            #    osp.join(out_dir, new_filename + "_label_viz" + ".png"))

    for name, value in label_value_dict.items():
        label_names[value] = name
#label.txt里的内容见下图
    with open("./label.txt", "w") as f:
        for lbl_name in label_names:
            f.write(lbl_name + "\n")

在这里插入图片描述

2. masks2binary

import cv2
import os


def convert_png2seg(input_dir,output_dir):
    files = os.listdir(input_dir)
    for file in files:
        part = file.split('.')
        part0 = part[0]
        part1 = part[1]
        img = cv2.imread(input_dir+file)
        img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

        #前景像素值变为255,背景像素值变为0
        retval, binary = cv2.threshold(img_gray, 10, 255, cv2.THRESH_BINARY)  #阈值处理
        cv2.imwrite(output_dir + part0 + '.' + part1, binary)


if __name__ == "__main__":
    #输入mask数据路径
    input_dir = r"./masks/"
    #binary后的图像输出路径
    output_dir = r"./output masks/"
    convert_png2seg(input_dir,output_dir)

3. 图像裁剪(对角坐标截取需要的图像区域)

import cv2
import os


def update(input_img_path, output_img_path):
    image = cv2.imread(input_img_path)
    #print(image.shape)
    #cropped = image[120:760, 25:1010]  # 裁剪坐标为[y0:y1, x0:x1]
    cropped = image[120:760, 100:940]
    cv2.imwrite(output_img_path, cropped)


dataset_dir = 'images/1'  # 需裁剪的图片存放文件夹
output_dir = 'out/1'  # 裁好图片输出文件夹

def auto_create_path(output_dir):
	if os.path.exists(output_dir):   ##目录存在,返回为真
	        print( 'dir exists'  )
	else:
	        print( 'dir not exists')
	        os.makedirs(output_dir)
	        #os.mkdir(FilePath)

auto_create_path(output_dir)


# 获得需要转化的图片路径并生成目标路径
image_filenames = [(os.path.join(dataset_dir, x), os.path.join(output_dir, x))
                   for x in os.listdir(dataset_dir)]
# 转化所有图片
for path in image_filenames:
    update(path[0], path[1])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

VisionX Lab

你的鼓励将是我更新的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值