{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import sys\nsys.path.insert(0, \"/kaggle/input/yolosoc/resources/Weighted-Boxes-Fusion\")\nsys.path.insert(0, '/kaggle/input/yolosoc/resources/yolov5')\n\nimport numpy as np # linear algebra\nimport os\nfrom tqdm.auto import tqdm\nimport shutil as sh\nimport torch\nimport cv2\nfrom ensemble_boxes import *\nfrom utils.augmentations import *\nfrom utils.general import *\nfrom glob import glob\n\nYOLO_CONF_THRES = 0.5\nYOLO_IOU_THRES = 0.6\nYOLO_IMG_SZ = 1024\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-05-23T09:58:48.792023Z","iopub.execute_input":"2023-05-23T09:58:48.792504Z","iopub.status.idle":"2023-05-23T09:58:48.801467Z","shell.execute_reply.started":"2023-05-23T09:58:48.792466Z","shell.execute_reply":"2023-05-23T09:58:48.800402Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def clip_coords(boxes, img_shape):\n    # Clip bounding xyxy bounding boxes to image shape (height, width)\n    boxes[:, 0].clamp_(0, img_shape[1])  # x1\n    boxes[:, 1].clamp_(0, img_shape[0])  # y1\n    boxes[:, 2].clamp_(0, img_shape[1])  # x2\n    boxes[:, 3].clamp_(0, img_shape[0])  # y2\n\ndef scale_coords(img1_shape, coords, img0_shape, ratio_pad=None):\n    # Rescale coords (xyxy) from img1_shape to img0_shape\n    if ratio_pad is None:  # calculate from img0_shape\n        gain = max(img1_shape) / max(img0_shape)  # gain  = old / new\n        pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2  # wh padding\n    else:\n        gain = ratio_pad[0][0]\n        pad = ratio_pad[1]\n\n    coords[:, [0, 2]] -= pad[0]  # x padding\n    coords[:, [1, 3]] -= pad[1]  # y padding\n    coords[:, :4] /= gain\n    clip_coords(coords, img0_shape)\n    return coords\n\ndef detectSingle(im0, imgsz, model, device, conf_thres, iou_thres):\n    img = letterbox(im0, new_shape=imgsz)[0]\n    # Convert\n    img = img[:, :, ::-1].transpose(2, 0, 1)  # BGR to RGB, to 3x416x416\n    img = np.ascontiguousarray(img)\n\n\n    img = torch.from_numpy(img).to(device)\n    img =  img.float()  # uint8 to fp16/32\n    img /= 255.0   \n    if img.ndimension() == 3:\n        img = img.unsqueeze(0)\n\n    # Inference\n    pred = model(img, augment=False)[0]\n\n    # Apply NMS\n    pred = non_max_suppression(pred, conf_thres, iou_thres)\n\n    boxes = []\n    scores = []\n    for i, det in enumerate(pred):  # detections per image\n        # save_path = 'draw/' + image_id + '.jpg'\n        if det is not None and len(det):\n            # Rescale boxes from img_size to im0 size\n            det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()\n\n            # Write results\n            for *xyxy, conf, cls in det:\n                boxes.append([int(xyxy[0]), int(xyxy[1]), int(xyxy[2]), int(xyxy[3])])\n                scores.append(conf)\n\n    return torch.tensor(boxes), torch.tensor(scores)\n\ndef format_prediction(boxes, scores):\n    pred_strings = []\n    for j in zip(scores, boxes):\n        pred_strings.append(f\"{j[0]:.4f} {j[1][0]} {j[1][1]} {j[1][2]} {j[1][3]}\")\n    return \" \".join(pred_strings)\n\ndef detect(weight_path, test_path):\n    device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n    model = torch.load(weight_path, map_location=device)['model'].to(device).float().eval()\n\n    image_ids=np.array([path.split('/')[-1][:-4] for path in glob(f'{test_path}/*.jpg')])\n    results = []\n    for image_id in image_ids:\n        try:\n            image_path = f'{test_path}/{image_id}.jpg'\n            im01 = cv2.imread(image_path)  # BGR\n            assert im01 is not None, 'Image Not Found ' + name\n            # Padded resize\n            im_w, im_h = im01.shape[:2]\n\n            boxes, scores = detectSingle(im01, YOLO_IMG_SZ, model, device, YOLO_CONF_THRES, YOLO_IOU_THRES)\n\n            boxes[:, 2] = boxes[:, 2] - boxes[:, 0]\n            boxes[:, 3] = boxes[:, 3] - boxes[:, 1]\n\n            boxes = boxes[scores >= 0.05].type(torch.int32)\n            scores = scores[scores >=float(0.05)]\n\n            result = {\n                'image_id': image_id,\n                'PredictionString': format_prediction(boxes, scores)\n            }\n            results.append(result)\n        except Exception as e:\n            result = {\n                'image_id': image_id,\n                'PredictionString': ''\n            }\n            results.append(result)\n    return results","metadata":{"execution":{"iopub.status.busy":"2023-05-23T09:58:48.822886Z","iopub.execute_input":"2023-05-23T09:58:48.823471Z","iopub.status.idle":"2023-05-23T09:58:48.846934Z","shell.execute_reply.started":"2023-05-23T09:58:48.823438Z","shell.execute_reply":"2023-05-23T09:58:48.846003Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results = detect('/kaggle/input/soc-yolo/resources/yolov5/runs/train/exp4/weights/best.pt', '/kaggle/input/global-wheat-detection/test')\ntest_df = pd.DataFrame(results, columns=['image_id', 'PredictionString'])\ntest_df.to_csv('submission.csv', index=False)\ntest_df.head()","metadata":{"execution":{"iopub.status.busy":"2023-05-23T09:58:48.848990Z","iopub.execute_input":"2023-05-23T09:58:48.849403Z","iopub.status.idle":"2023-05-23T09:59:46.023155Z","shell.execute_reply.started":"2023-05-23T09:58:48.849374Z","shell.execute_reply":"2023-05-23T09:59:46.022062Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}