{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np \nimport pandas as pd \nimport os\n\ntrain_path = '../input/global-wheat-detection/train.csv'\ndf = pd.read_csv(train_path)\n\nbbox = np.stack(df['bbox'].apply(lambda x: np.fromstring(x[1:-1], sep=',')))\nfor i,col_name in enumerate(['x','y','w','h']):\n    df[col_name] = bbox[:,i]\ndf['center_x'] = df['x'] + df['w']/2\ndf['center_y'] = df['y'] + df['h']/2\ndf['classes'] = 0\n\ndf = df[['image_id','x', 'y', 'w', 'h','center_x','center_y','classes']]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!cp -r ../input/yolov5train/* .","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from utils.datasets import *\nfrom utils.utils import * ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import sys\nsys.path.insert(0, \"../input/weightedboxesfusion\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class opt:\n        weights = \"../input/wheatyolo/best_wheat.pt\"\n        img_size = 1024\n        conf_thres = 0.3\n        iou_thres = 0.4\n        augment = True\n        device = '0'\n        classes=None\n        agnostic_nms = True\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    \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\n    img = torch.zeros((1, 3, imgsz, imgsz), device=device)  # init img\n\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\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\n            if True:\n                pred = model(img, augment=opt.augment)[0]\n                pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=None, agnostic=False)\n                t2 = torch_utils.time_synchronized()\n\n                bboxes = []\n                score = []\n\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\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()  \n\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#opt.img_size = check_img_size(opt.img_size)\n\nwith torch.no_grad():\n    res = detect()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"all_path,all_score,all_bboxex = res  ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def run_wbf(boxes,scores, image_size=1024, iou_thr=0.6, skip_box_thr=0.24, weights=None):\n#     boxes =boxes/(image_size-1)\n    \n    labels0 = [np.ones(len(scores[idx])) for idx in range(len(scores))]\n    boxes, scores, labels = weighted_boxes_fusion(boxes, scores, labels0, weights=None, iou_thr=iou_thr, skip_box_thr=skip_box_thr)\n    \n    #     boxes = boxes*(image_size-1)\n#     boxes = boxes\n    \n    return boxes, scores, labels","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#!pip install ensemble-boxes\nfrom ensemble_boxes import *","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results =[]\n\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)\n\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    print(type(boxes))\n    boxes, scores, labels = run_wbf(boxes,scores)\n    boxes = np.array(boxes)\n    print(boxes.shape)\n    boxes = (boxes*1024/1024).astype(np.int32).clip(min=0, max=1023)\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'])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(test_df.head(10))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.to_csv('submission.csv', index = False)","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}