Spaces:
Sleeping
Sleeping
File size: 4,598 Bytes
0742dfe |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 |
# -*- coding: utf-8 -*-
import time
import json
import cv2
import torch
import numpy as np
import matplotlib.pyplot as plt
def setup_logger(log_file_path: str = None):
import logging
from colorlog import ColoredFormatter
logging.basicConfig(filename=log_file_path,
format='%(asctime)s %(levelname)-8s %(filename)s[line:%(lineno)d]: %(message)s',
# 定义输出log的格式
datefmt='%Y-%m-%d %H:%M:%S', )
"""Return a logger with a default ColoredFormatter."""
formatter = ColoredFormatter(
"%(asctime)s %(log_color)s%(levelname)-8s %(reset)s %(filename)s[line:%(lineno)d]: %(message)s",
datefmt='%Y-%m-%d %H:%M:%S',
reset=True,
log_colors={
'DEBUG': 'blue',
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'red',
})
logger = logging.getLogger('PAN')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
logger.info('logger init finished')
return logger
# --exeTime
def exe_time(func):
def newFunc(*args, **args2):
t0 = time.time()
back = func(*args, **args2)
print("{} cost {:.3f}s".format(func.__name__, time.time() - t0))
return back
return newFunc
def save_json(data, json_path):
with open(json_path, mode='w', encoding='utf8') as f:
json.dump(data, f, indent=4)
def load_json(json_path):
with open(json_path, mode='r', encoding='utf8') as f:
data = json.load(f)
return data
def show_img(imgs: np.ndarray, color=False):
if (len(imgs.shape) == 3 and color) or (len(imgs.shape) == 2 and not color):
imgs = np.expand_dims(imgs, axis=0)
for img in imgs:
plt.figure()
plt.imshow(img, cmap=None if color else 'gray')
def draw_bbox(img_path, result, color=(128, 240, 128), thickness=3):
if isinstance(img_path, str):
img_path = cv2.imread(img_path)
# img_path = cv2.cvtColor(img_path, cv2.COLOR_BGR2RGB)
img_path = img_path.copy()
for point in result:
point = point.astype(int)
cv2.line(img_path, tuple(point[0]), tuple(point[1]), color, thickness)
cv2.line(img_path, tuple(point[1]), tuple(point[2]), color, thickness)
cv2.line(img_path, tuple(point[2]), tuple(point[3]), color, thickness)
cv2.line(img_path, tuple(point[3]), tuple(point[0]), color, thickness)
return img_path
def cal_text_score(texts, gt_texts, training_masks, running_metric_text):
training_masks = training_masks.data.cpu().numpy()
pred_text = torch.sigmoid(texts).data.cpu().numpy() * training_masks
pred_text[pred_text <= 0.5] = 0
pred_text[pred_text > 0.5] = 1
pred_text = pred_text.astype(np.int32)
gt_text = gt_texts.data.cpu().numpy() * training_masks
gt_text = gt_text.astype(np.int32)
running_metric_text.update(gt_text, pred_text)
score_text, _ = running_metric_text.get_scores()
return score_text
def cal_kernel_score(kernel, gt_kernel, gt_texts, training_masks, running_metric_kernel):
mask = (gt_texts * training_masks.float()).data.cpu().numpy()
pred_kernel = torch.sigmoid(kernel).data.cpu().numpy()
pred_kernel[pred_kernel <= 0.5] = 0
pred_kernel[pred_kernel > 0.5] = 1
pred_kernel = (pred_kernel * mask).astype(np.int32)
gt_kernel = gt_kernel.data.cpu().numpy()
gt_kernel = (gt_kernel * mask).astype(np.int32)
running_metric_kernel.update(gt_kernel, pred_kernel)
score_kernel, _ = running_metric_kernel.get_scores()
return score_kernel
def order_points_clockwise(pts):
rect = np.zeros((4, 2), dtype="float32")
s = pts.sum(axis=1)
rect[0] = pts[np.argmin(s)]
rect[2] = pts[np.argmax(s)]
diff = np.diff(pts, axis=1)
rect[1] = pts[np.argmin(diff)]
rect[3] = pts[np.argmax(diff)]
return rect
def order_points_clockwise_list(pts):
pts = pts.tolist()
pts.sort(key=lambda x: (x[1], x[0]))
pts[:2] = sorted(pts[:2], key=lambda x: x[0])
pts[2:] = sorted(pts[2:], key=lambda x: -x[0])
pts = np.array(pts)
return pts
if __name__ == '__main__':
#box = np.array([382, 1080, 443, 999, 423, 1014, 362, 1095]).reshape(-1, 2)
box = np.array([0, 4, 2, 2, 0, 8, 4, 4]).reshape(-1, 2)
# box = np.array([0, 0, 2, 2, 0, 4, 4, 4]).reshape(-1, 2)
from scipy.spatial import ConvexHull
print(box)
print(order_points_clockwise(box))
print(order_points_clockwise_list(box))
|