在图片中随机采样,而且不与已经标注的物体重合,啥也不说直接上代码:
"""
在图片随机采样宽为150,高为80的负样本
"""
import os
import json
import random
import cv2
import numpy as np
oimg_path = r"C:\Users\9ling\Desktop\YiLiuWuDataset_hardsample\original_dataset\yuedongguan_01"
ojson_path = r"C:\Users\9ling\Desktop\YiLiuWuDataset_hardsample\original_dataset\yuedongguan_01.json"
train_imgpath = r"C:\Users\9ling\Desktop\YiLiuWuDataset_hardsample\YiliuwuDataset\train\yuedongguan01"
train_jsonpath = r"C:\Users\9ling\Desktop\YiLiuWuDataset_hardsample\YiliuwuDataset\train\yuedongguan01\yuedongguan01.json"
def IoU(boxA, boxB):
boxA = [int(x) for x in boxA]
boxB = [int(x) for x in boxB]
xA = max(boxA[0], boxB[0])
yA = max(boxA[1], boxB[1])
xB = min(boxA[2], boxB[2])
yB = min(boxA[3], boxB[3])
interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)
boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)
boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)
iou = interArea / float(boxAArea + boxBArea - interArea)
return iou
json_list = {"labels": []}
def gain(ojson_path):
jdata = json.load(open(ojson_path))["labels"]
for item in jdata:
sImg_path = os.path.join(oimg_path, item["filename"].split("\\")[-1])
im = cv2.imdecode(np.fromfile(sImg_path), 1)
height, width = im.shape[:-1]
while True:
rlist = []
rx1 = random.choice(range(1, width - 150 - 1, 1))
ry1 = random.choice(range(1, height - 80 - 1, 1))
rx2 = min(rx1 + 150, width - 1)
ry2 = min(ry1 + 80, height - 1)
rlist.extend([rx1, ry1, rx2, ry2])
sum_ious = 0
for anno in item["annotations"]:
alist = []
ax1 = anno["x"]
ay1 = anno["y"]
ax2 = ax1 + anno["width"] - 1
ay2 = ay1 + anno["height"] - 1
alist.extend([ax1, ay1, ax2, ay2])
if IoU(rlist, alist) == 0:
sum_ious += IoU(rlist, alist)
continue
else:
sum_ious += IoU(rlist, alist)
break
if sum_ious == 0:
item["annotations"].append({"class": "negativesample01",
"height": ry2 - ry1 + 1,
"width": rx2 - rx1 + 1,
"x": rx1,
"y": ry1})
break
json_list["labels"].append(item)
gain(ojson_path)
json_test_str = json.dumps(json_list, indent=4)
with open(train_jsonpath, 'w') as json_file:
json_file.write(json_test_str)