{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np \nimport pandas as pd \nimport os","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import torch\nimport sys\nsys.path.insert(0, \"../input/weightedbf/Weighted-Boxes-Fusion-master\")\nsys.path.append(\"../input/yolov5utils\")\nfrom ensemble_boxes import *\nimport glob","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import argparse\n\nfrom utils.datasets import *\nfrom utils.utils import *\n\n\ndef detect(save_img=False):\n    weights, imgsz = opt.weights,opt.img_size\n    source = '../input/global-wheat-detection/test/'\n    \n    # Initialize\n    device = torch_utils.select_device(opt.device)\n    half = False\n    # Load model\n\n    model = torch.load(weights, map_location=device)['model'].to(device).float().eval()\n\n    dataset = LoadImages(source, img_size=1024)\n\n    t0 = time.time()\n    img = torch.zeros((1, 3, imgsz, imgsz), device=device)  # init img\n    all_path=[]\n    all_bboxex =[]\n    all_score =[]\n    for path, img, im0s, vid_cap in dataset:\n        print(im0s.shape)\n        img = torch.from_numpy(img).to(device)\n        img = img.half() if half else img.float()  # uint8 to fp16/32\n        img /= 255.0  # 0 - 255 to 0.0 - 1.0\n        if img.ndimension() == 3:\n            img = img.unsqueeze(0)\n\n        # Inference\n        t1 = torch_utils.time_synchronized()\n        bboxes_2 = []\n        score_2 = []\n        if True:\n            pred = model(img, augment=opt.augment)[0]\n            # pred = non_max_suppression(pred, 0.4, opt.iou_thres,fast=True, classes=None, agnostic=False)\n            pred = non_max_suppression(pred, 0.4, opt.iou_thres, classes=None, agnostic=False)\n            t2 = torch_utils.time_synchronized()\n\n            bboxes = []\n            score = []\n            # Process detections\n            for i, det in enumerate(pred):  # detections per image\n                p, s, im0 = path, '', im0s\n                gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  #  normalization gain whwh\n                if det is not None and len(det):\n                    det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()\n                    for c in det[:, -1].unique():\n                        n = (det[:, -1] == c).sum()  # detections per class\n\n                    for *xyxy, conf, cls in det:\n                        if True:  # Write to file\n                            xywh = torch.tensor(xyxy).view(-1).numpy()  # normalized xywh\n#                             xywh[2] = xywh[2]-xywh[0]\n#                             xywh[3] = xywh[3]-xywh[1]\n                            bboxes.append(xywh)\n                            score.append(conf)\n            bboxes_2.append(bboxes)\n            score_2.append(score)\n        all_path.append(path)\n        all_score.append(score_2)\n        all_bboxex.append(bboxes_2)\n    return all_path,all_score,all_bboxex\n\n\nif __name__ == '__main__':\n    class opt:\n        weights = \"../input/yolo-v5-weight/best_yolov5x_fold0.pt\"\n        img_size = 1024\n        conf_thres = 0.1\n        iou_thres = 0.94\n        augment = True\n        device = '0'\n        classes=None\n        agnostic_nms = True\n        \n    opt.img_size = check_img_size(opt.img_size)\n    print(opt)\n\n    with torch.no_grad():\n        res = detect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"all_path,all_score,all_bboxex = res\ndef run_wbf(boxes,scores):\n    all_scores = []\n    all_bboxes = []\n    all_labels = []\n    all_scores.append(list(np.array([scores[0][j].cpu().numpy() for j in range(len(scores[0]))])))\n    all_bboxes.append([list(item / 1024) for item in boxes[0]])\n    all_labels.append([0 for i in range(len(boxes[0]))])\n#     print(all_scores)\n    boxes, scores, labels = weighted_boxes_fusion(all_bboxes, all_scores, all_labels)\n    return boxes, scores, labels\n# run_wbf(all_bboxex[0], all_score[0])\n# all_bboxex","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results =[]\ndef format_prediction_string(boxes, scores):\n    pred_strings = []\n    for j in zip(scores, boxes):\n        pred_strings.append(\"{0:.4f} {1} {2} {3} {4}\".format(j[0], j[1][0], j[1][1], j[1][2], j[1][3]))\n    return \" \".join(pred_strings)\nfor row in range(len(all_path)):\n    image_id = all_path[row].split(\"/\")[-1].split(\".\")[0]\n    boxes = all_bboxex[row]\n    scores = all_score[row]\n    boxes, scores, labels = run_wbf(boxes,scores)\n#     print(boxes)\n#     print(scores)\n    boxes = (boxes*1024).astype(np.int32).clip(min=0, max=1023)\n#     print(boxes)\n    boxes[:, 2] = boxes[:, 2] - boxes[:, 0]\n    boxes[:, 3] = boxes[:, 3] - boxes[:, 1]\n    result = {'image_id': image_id,'PredictionString': format_prediction_string(boxes, scores)}\n    results.append(result)\ntest_df = pd.DataFrame(results, columns=['image_id', 'PredictionString'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.PredictionString.values[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.to_csv('submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}