裁掉图片中不需要的部分
注:
标注后的图片 images/ (jpg+json) 该脚本会读取图片 根据json中的标注点的位置 进行填充原始图片, 并将 json 文件中对应的标签移除;
#!/usr/bin/python3.6.10
# -*- coding: utf-8 -*-
# @Author :
# @Time : 2021/12/2 16:11
# @File : 裁掉图片中不需要的部分.py
import cv2
from pathlib import Path
import json
from tqdm import tqdm
from shutil import copyfile
from queue import Queue
import time
import numpy as np
from copy import deepcopy
def fillBlock(img_dir):
img_dir = Path(img_dir)
img_list = list(img_dir.glob('*.jpg'))
for img_path in tqdm(img_list):
img = cv2.imread(img_path.as_posix())
json_path = img_path.with_suffix('.json') # type:Path
with json_path.open('r', encoding='utf-8') as f:
labels = json.load(f)
shapes = labels['shapes'] # type:list
for shape in deepcopy(shapes):
if shape['label'] == '填充':
b = np.array([shape['points']], dtype=np.int32)
cv2.fillPoly(img, pts=b, color=(175, 175, 157))
shapes.remove(shape)
cv2.imwrite(img_path.as_posix(), img)
with json_path.open('w', encoding='utf-8') as f:
json.dump(labels, f, ensure_ascii=False, indent=2)
if __name__ == '__main__':
"""
先用标注工具多边形标注 至少三个点,闭合空间;"填充";
"""
img_dir = r'C:\Users\xxx\Desktop\test_json\fuben\top'
fillBlock(img_dir)