# -*- coding:utf-8 -*-
import os
import json
import cv2
label_pth = "/home/li/pytest/yolt/yang_ship_val/ship_val_labels.txt"
img_dir = "/home/li/pytest/yolt/yang_ship_val/val_images"
save_dir = "/home/li/pytest/yolt/yang_ship_val/val_vis"
def json_label(json_pth,label_pth):
with open(json_pth,encoding="utf-8") as f:
with open(label_pth,"a+") as fn:
d = json.load(f)
img_name = d["imagePath"]
img_pth = os.path.join(img_dir,img_name)
img = cv2.imread(img_pth)
h,w,_ = img.shape
fn.write(img_name)
fn.write(" ")
fn.write(str(w))
fn.write(" ")
fn.write(str(h))
fn.write(" ")
for i in range(len(d["shapes"])):
label = d["shapes"][i]["label"]
points = d["shapes"][i]["points"]
x0 = points[0][0]
y0 = points[0][1]
x1 = points[0][0]
y1 = points[0][1]
for j in range(len(points)):
x0 = x0 if x0 < points[j][0] else points[j][0]
y0 = y0 if y0 < points[j][1] else points[j][1]
x1 = x1 if x1 > points[j][0] else points[j][0]
y1 = y1 if y1 > points[j][1] else points[j][1]
fn.write(str(x0))
fn.write(" ")
fn.write(str(y0))
fn.write(" ")
fn.write(str(x1))
fn.write(" ")
fn.write(str(y1))
fn.write(" ")
fn.write(label)
fn.write(" ")
fn.write("\n")
# json_dir = "/home/li/pytest/yolt/yang_ship_val/labels"
# for root,_,file_name in os.walk(json_dir):
# for name in file_name:
# json_pth = os.path.join(json_dir,name)
# json_label(json_pth,label_pth)
def test_vis(label_pth,img_dir,save_dir):
with open(label_pth,"r") as f:
for line in f.readlines():
splited = line.strip().split(" ")
img_name = splited[0]
img_pth = os.path.join(img_dir,img_name)
img = cv2.imread(img_pth)
for i in range(int((len(splited)-3)/5)):
x0 = int(splited[5*i+3])
y0 = int(splited[5*i+4])
x1 = int(splited[5*i+5])
y1 = int(splited[5*i+6])
cv2.rectangle(img,(x0,y0),(x1,y1),color=[0,255,0],thickness=2)
save_pth = os.path.join(save_dir,img_name)
cv2.imwrite(save_pth,img)
test_vis(label_pth,img_dir,save_dir)