def correct_box(box_xy: tf.Tensor, box_wh: tf.Tensor, input_shape: list, image_shape: list) -> tf.Tensor: """rescae predict box to orginal image scale Parameters ---------- box_xy : tf.Tensor box xy box_wh : tf.Tensor box wh input_shape : list input shape image_shape : list image shape Returns ------- tf.Tensor new boxes """ box_yx = box_xy[..., ::-1] box_hw = box_wh[..., ::-1] input_shape = tf.cast(input_shape, tf.float32) image_shape = tf.cast(image_shape, tf.float32) new_shape = tf.round(image_shape * tf.reduce_min(input_shape / image_shape)) offset = (input_shape - new_shape) / 2. / input_shape scale = input_shape / new_shape box_yx = (box_yx - offset) * scale box_hw *= scale box_mins = box_yx - (box_hw / 2.) box_maxes = box_yx + (box_hw / 2.) boxes = tf.concat( [ box_mins[..., 0:1], # y_min box_mins[..., 1:2], # x_min box_maxes[..., 0:1], # y_max box_maxes[..., 1:2] # x_max ], axis=-1) # Scale boxes back to original image shape. boxes *= tf.concat([image_shape, image_shape], axis=-1) return boxes
def _process_img(self, img: np.ndarray, true_box: np.ndarray, is_training: bool, is_resize: bool) -> tuple: """ process image and true box , if is training then use data augmenter Parameters ---------- img : np.ndarray image srs true_box : np.ndarray box is_training : bool wether to use data augmenter is_resize : bool wether to resize the image Returns ------- tuple image src , true box """ if is_resize: """ resize image and keep ratio """ img_wh = np.array([img.shape[1], img.shape[0]]) in_wh = self.in_hw[0][::-1] """ calculate the affine transform factor """ scale = in_wh / img_wh # NOTE affine tranform sacle is [w,h] scale[:] = np.min(scale) # NOTE translation is [w offset,h offset] translation = ((in_wh - img_wh * scale) / 2).astype(int) """ calculate the box transform matrix """ if isinstance(true_box, np.ndarray): true_box[:, 1:3] = (true_box[:, 1:3] * img_wh * scale + translation) / in_wh true_box[:, 3:5] = (true_box[:, 3:5] * img_wh * scale) / in_wh elif isinstance(true_box, tf.Tensor): # NOTE use concat replace item assign true_box = tf.concat( (true_box[:, 0:1], (true_box[:, 1:3] * img_wh * scale + translation) / in_wh, (true_box[:, 3:5] * img_wh * scale) / in_wh), axis=1) """ apply Affine Transform """ aff = skimage.transform.AffineTransform(scale=scale, translation=translation) img = skimage.transform.warp(img, aff.inverse, output_shape=self.in_hw[0], preserve_range=True).astype('uint8') if is_training: img, true_box = self.data_augmenter(img, true_box) # normlize image img = img / np.max(img) return img, true_box
def main(ckpt_weights, image_size, output_size, model_def, class_num, depth_multiplier, obj_thresh, iou_thresh, train_set, test_image): h = Helper(None, class_num, f'data/{train_set}_anchor.npy', np.reshape(np.array(image_size), (-1, 2)), np.reshape(np.array(output_size), (-1, 2))) network = eval(model_def) # type :yolo_mobilev2 yolo_model, yolo_model_warpper = network([image_size[0], image_size[1], 3], len(h.anchors[0]), class_num, alpha=depth_multiplier) yolo_model_warpper.load_weights(str(ckpt_weights)) print(INFO, f' Load CKPT {str(ckpt_weights)}') orig_img = h._read_img(str(test_image)) image_shape = orig_img.shape[0:2] img, _ = h._process_img(orig_img, true_box=None, is_training=False, is_resize=True) """ load images """ img = tf.expand_dims(img, 0) y_pred = yolo_model_warpper.predict(img) """ box list """ _yxyx_box = [] _yxyx_box_scores = [] """ preprocess label """ for l, pred_label in enumerate(y_pred): """ split the label """ pred_xy = pred_label[..., 0:2] pred_wh = pred_label[..., 2:4] pred_confidence = pred_label[..., 4:5] pred_cls = pred_label[..., 5:] # box_scores = obj_score * class_score box_scores = tf.sigmoid(pred_cls) * tf.sigmoid(pred_confidence) # obj_mask = pred_confidence_score[..., 0] > obj_thresh """ reshape box """ # NOTE tf_xywh_to_all will auto use sigmoid function pred_xy_A, pred_wh_A = tf_xywh_to_all(pred_xy, pred_wh, l, h) boxes = correct_box(pred_xy_A, pred_wh_A, image_size, image_shape) boxes = tf.reshape(boxes, (-1, 4)) box_scores = tf.reshape(box_scores, (-1, class_num)) """ append box and scores to global list """ _yxyx_box.append(boxes) _yxyx_box_scores.append(box_scores) yxyx_box = tf.concat(_yxyx_box, axis=0) yxyx_box_scores = tf.concat(_yxyx_box_scores, axis=0) mask = yxyx_box_scores >= obj_thresh """ do nms for every classes""" _boxes = [] _scores = [] _classes = [] for c in range(class_num): class_boxes = tf.boolean_mask(yxyx_box, mask[:, c]) class_box_scores = tf.boolean_mask(yxyx_box_scores[:, c], mask[:, c]) select = tf.image.non_max_suppression(class_boxes, scores=class_box_scores, max_output_size=30, iou_threshold=iou_thresh) class_boxes = tf.gather(class_boxes, select) class_box_scores = tf.gather(class_box_scores, select) _boxes.append(class_boxes) _scores.append(class_box_scores) _classes.append(tf.ones_like(class_box_scores) * c) boxes = tf.concat(_boxes, axis=0) classes = tf.concat(_classes, axis=0) scores = tf.concat(_scores, axis=0) """ draw box """ font = ImageFont.truetype(font='asset/FiraMono-Medium.otf', size=tf.cast( tf.floor(3e-2 * image_shape[0] + 0.5), tf.int32).numpy()) thickness = (image_shape[0] + image_shape[1]) // 300 """ show result """ if len(classes) > 0: pil_img = Image.fromarray(orig_img) print(f'[top\tleft\tbottom\tright\tscore\tclass]') for i, c in enumerate(classes): box = boxes[i] score = scores[i] label = '{:2d} {:.2f}'.format(int(c.numpy()), score.numpy()) draw = ImageDraw.Draw(pil_img) label_size = draw.textsize(label, font) top, left, bottom, right = box print( f'[{top:.1f}\t{left:.1f}\t{bottom:.1f}\t{right:.1f}\t{score:.2f}\t{int(c):2d}]' ) top = max(0, tf.cast(tf.floor(top + 0.5), tf.int32)) left = max(0, tf.cast(tf.floor(left + 0.5), tf.int32)) bottom = min(image_shape[0], tf.cast(tf.floor(bottom + 0.5), tf.int32)) right = min(image_shape[1], tf.cast(tf.floor(right + 0.5), tf.int32)) if top - image_shape[0] >= 0: text_origin = tf.convert_to_tensor([left, top - label_size[1]]) else: text_origin = tf.convert_to_tensor([left, top + 1]) for j in range(thickness): draw.rectangle([left + j, top + j, right - j, bottom - j], outline=h.colormap[c]) draw.rectangle( [tuple(text_origin), tuple(text_origin + label_size)], fill=h.colormap[c]) draw.text(text_origin, label, fill=(0, 0, 0), font=font) del draw pil_img.show() else: print(NOTE, ' no boxes detected')