'''
切成单类别小图并放入TEA_CHECK\CLS_Folder文件夹中
'''
Org_Img_Path = 'C:\work\sun\datasets\RedTeaV\RedTeaV_L5_Product_III_train.txt'
Org_Json_Path = Org_Img_Path
Threshold_and = 25
Threshold_or = 10
DarwPoint = False
distination = "C:\work\sun\datasets\RedTeaV\RedTeaV_L5_Product"
###################################################################################
if __name__ == '__main__':
if not os.path.exists(distination):
os.makedirs(distination)
if os.path.isfile(Org_Img_Path) and Org_Img_Path.endswith("txt"):
with open(Org_Img_Path) as fx:
line = fx.read().strip().splitlines()
Img_Files = [item for item in line if item.split(".")[-1] in ["jpg","bmp","png"]]
else:
Img_Files = glob.glob(Org_Img_Path + "\*.jpg")+glob.glob(Org_Img_Path + "\*.bmp")+glob.glob(Org_Img_Path + "\*.png")
for idx, Img_File in tqdm(enumerate(Img_Files),total=len(Img_Files)):
imgItem = os.path.basename(Img_File)
JsonItem = imgItem.replace(imgItem.split(".")[-1],"json")
json_File = Img_File.replace(Img_File.split(".")[-1],"json")
if not os.path.isfile(json_File):
print("{} do not have same Name json !".format(json_File))
continue
im0s = cv2.imread(Img_File)
data = json.load(open(json_File))
box_list = []
point_list = []
for shape in data['shapes']:
if shape['shape_type'] == 'rectangle':
box_list.append(shape)
elif shape['shape_type'] == 'point':
point_list.append(shape)
if len(box_list)==1:
for id , (box_shape, point_shape) in enumerate(zip(box_list,point_list)):
label_name = box_shape['label']
folder_cls = os.path.join(distination, label_name)
if not os.path.exists(folder_cls):
os.mkdir(folder_cls)
label_point = box_shape['points']
label_point = np.array(label_point).astype(np.int32)
X1,Y1,X2,Y2 = label_point[0][0], label_point[0][1], label_point[1][0], label_point[1][1]
Xmin, Ymin = min(X1, X2), min(Y1, Y2)
Xmax, Ymax = max(X1, X2), max(Y1, Y2)
Xmin,Ymin,Xmax,Ymax = max(int(Xmin),0),max(int(Ymin),0),min(max(int(Xmax),0),im0s.shape[1]) , min(max(int(Ymax),0),im0s.shape[0])
KeyPoint = np.array(point_shape['points']).flatten().astype(np.int32)
KeyPoint_X, KeyPoint_Y = KeyPoint[0], KeyPoint[1]
KeyPoint_X, KeyPoint_Y = KeyPoint_X - Xmin, KeyPoint_Y - Ymin
if (Ymax - Ymin) < Threshold_and and (Xmax - Xmin) < Threshold_and:
continue
if (Ymax - Ymin) < Threshold_or or (Xmax - Xmin) < Threshold_or:
continue
SMImg = im0s[Ymin:Ymax, Xmin:Xmax, :]
KeyPoint_X, KeyPoint_Y = round(KeyPoint_X), round(KeyPoint_Y)
if DarwPoint:
cv2.circle(SMImg, (KeyPoint_X, KeyPoint_Y), 5, (0, 0, 255), -1)
keyPoint_str = str(KeyPoint_X) + "," + str(KeyPoint_Y)
name = 'im_' + imgItem.split(".")[-2] + '_' + format(str(id), '0>3s') + "_X" + str(KeyPoint_X) + "_Y" + str(KeyPoint_Y) + '_.png'
box_str = str(X1) + "," + str(Y1) + "," + str(X2) + "," + str(Y2)
save_path = os.path.join(folder_cls, name)
cv2.imwrite(save_path, SMImg)
将Labelme标注的图片按种类进行切割成小图片
于 2024-05-17 13:42:42 首次发布