ROI裁剪图片和生成新的Json标签文件

标注裁剪区域命名为ROI,ROI内有其他的标签,例如:裂纹等。根据ROI裁剪出新的图片和标签文件。

import json
import os
from copy import deepcopy
import cv2
import argparse
from tqdm import tqdm
parser = argparse.ArgumentParser("import args")
parser.add_argument("--img2json",default=r'.GS_27',type=str,help="input to path")
parser.add_argument("--add2piexl",default={"patch":[0,0]
                                           },
                    type=dict,help="add to piexl")
parser.add_argument("--choice2gw",default=r"patch",type=str,help="choice to GW")
parser.add_argument("--tab",default=["ROI"],type=list,help="crop to tab")  ## ROI名称
args=parser.parse_args()
save2img_json=os.path.join(args.img2json,"ROI")  #扩充后
if not os.path.exists(save2img_json):
    os.makedirs(save2img_json)
img_type = "png"    ##  注意图片格式

def crop_json(ROI_json,new_name,ROI_coordinate):

    ROI_w = ROI_coordinate[2] - ROI_coordinate[0]
    ROI_h = ROI_coordinate[3] - ROI_coordinate[1]
    init_ROI = deepcopy(ROI_json)
    init_ROI['shapes'] = []
    init_ROI['imagePath'] = new_name
    init_ROI['imageData'] = None
    init_ROI['imageHeight'] = ROI_h
    init_ROI['imageWidth'] = ROI_w
    for shape in ROI_json["shapes"]:
        if shape["label"] not in args.tab:
            box_w = abs(int(shape["points"][0][0] - shape["points"][1][0]))
            box_h = abs(int(shape["points"][0][1]  - shape["points"][1][1]))
            xmin = max(0,int(shape["points"][0][0] - ROI_coordinate[0]))
            ymin = max(0,int(shape["points"][0][1] - ROI_coordinate[1]))
            xmax = min(ROI_w,int(shape["points"][1][0] - ROI_coordinate[0]))
            ymax = min(ROI_h,int(shape["points"][1][1] - ROI_coordinate[1]))

            if (xmax-xmin) >box_w*0.2 and (ymax-ymin) > box_h*0.2 and xmax>0 and ymax>0:
                shape_tmp = deepcopy(shape)
                shape_tmp["points"] = [[xmin,ymin],[xmax,ymax]]
                init_ROI['shapes'].append(shape_tmp)

    return init_ROI

def main():
    img2json = os.listdir(args.img2json)
    for item in tqdm(img2json):
        if item.endswith(".json"):
            jsonData = open(os.path.join(args.img2json, item), "r", encoding="utf8").read()
            jsonData = json.loads(jsonData)
            org_img = cv2.imread(os.path.join(args.img2json, item.replace("json", img_type)))  # shape=[h,w,c]
            imageHeight = jsonData["imageHeight"]
            imageWidth = jsonData["imageWidth"]
            cout = 0
            for shape in jsonData["shapes"]:
                tab_ROI = []
                if shape["label"] in args.tab:
                    xmin = max(0,int(shape["points"][0][0]))
                    ymin = max(0, int(shape["points"][0][1]))
                    xmax = min(imageWidth, int(shape["points"][1][0]))
                    ymax = min(imageHeight, int(shape["points"][1][1]))
                    if xmin > xmax:
                        xmin,xmax = xmax,xmin
                    if ymin > ymax:
                        ymin,ymax = ymax,ymin
                    tab_ROI=[xmin,ymin,xmax,ymax]
                    new_name = item.replace(".json","") + "_"+str(cout) + "."+img_type
                    cout +=1
                    ROI_img =  org_img[tab_ROI[1]:tab_ROI[3],tab_ROI[0]:tab_ROI[2],:]
                    ROI_json = crop_json(jsonData,new_name,tab_ROI)
                    if len(ROI_json['shapes']) >0:
                        try:
                            cv2.imwrite(os.path.join(save2img_json,new_name),ROI_img)
                            with open(os.path.join(save2img_json, new_name.replace(".png", ".json")), 'w') as file:
                                json.dump(ROI_json, file, indent=4)
                        except:
                            print("未知错误:{}".format(item))



if __name__ == '__main__':
    main()