因为在大图上进行使用labelme进行了标注,但在实际训练过程中发现大图(大概4000x4000)训练的结果并不好,小目标尺寸相比之下非常小(50x50),所以考虑将大图进行裁剪后再进行训练,同时根据已经标注好的json格式文件生成对应的小图的标注。
#将一整张大图切分成多张小图并修改对应的json标注
import cv2
import json
import os
# 读取大图的JSON文件
def splitImgandJson(IPath_json, IPath_img, OPath_json, OPath_img):
events = os.listdir(IPath_json)
#循环处理每一张图像和标注
for onevent in events:
name = onevent.split('.json')[0]
img_name = name + '.jpg'
with open(os.path.join(IPath_json, onevent), 'r') as json_file:
large_json_data = json.load(json_file)
# 读取大图的JPEG图像
large_image = cv2.imread(os.path.join(IPath_img, img_name))
# 定义每个小图的大小
crop_width, crop_height = 500, 500 # 可以根据需要调整大小
# 循环裁剪图像并生成新的JSON文件
L_H = large_image.shape[0]
L_W = large_image.shape[1]
for i in range(0, L_H, crop_height):
for j in range(0, L_W, crop_width):
# 裁剪图像
small_image = large_image[i:i + crop_height, j:j + crop_width]
# 创建新的JSON数据,基于大图的JSON数据进行调整
small_json_data = large_json_data.copy()
# 遍历大图标注看是否存在在小图中
new_target = [] # 替换'shapes'
for items in large_json_data[('shapes')]:
# 提取边界框坐标
x1, y1 = items["points"][0]
x2, y2 = items["points"][1]
# 判断目标框在小图中的位置
# 1、目标框全在小图中
new_item = items.copy()
if (j |