{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Importing all the libraries","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"#importing all the packages\nimport torch\nimport torchvision\nfrom tqdm import tqdm\nimport pandas as pd\nimport numpy as np\nimport os\nfrom glob import glob\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\nimport seaborn as sns\nimport shutil\nsns.set()\nimport cv2\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%cd ../input/yolov5","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Yolo inference","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"#Our inference method\n\nimport 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 = '/kaggle/input/global-wheat-detection/test'\n   \n    \n    # Initialize\n    device = torch_utils.select_device(opt.device)\n    half = device.type != 'cpu'\n    \n\n    #half = False\n    # Load model\n\n    model = torch.load(weights, map_location=device)['model'].to(device).eval()\n    if half:\n      model.half() \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    \n    results=[]\n    _ = model(img.half() if half else img) if device.type != 'cpu' else None  # run once\n    for path, img, im0s, vid_cap in dataset:\n        print(im0s.shape)\n        im0s = cv2.cvtColor(im0s, cv2.COLOR_BGR2RGB)\n        image_id = path.split(\"/\")[-1].split(\".\")[0]\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        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=True)\n            t2 = torch_utils.time_synchronized()\n            box_scores = []\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 = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()\n                            c1, c2 = (int(xyxy[0]), int(xyxy[1])), (int(xyxy[2]) - int(xyxy[0]), int(xyxy[3]) - int(xyxy[1]))\n                            box_scores.append(f\"{round(conf.item(),2)} {c1[0]} {c1[1]} {c2[0]} {c2[1]}\")\n                            cv2.putText(im0s, '{:.2}'.format(conf.item()), (c1[0],c1[1]-10), cv2.FONT_HERSHEY_SIMPLEX ,1, (255,255,255), 2, cv2.LINE_AA)\n#                             cc1, cc2 = (int(xyxy[0]), int(xyxy[1])), (int(xyxy[2]) , int(xyxy[3]))\n                            cv2.rectangle(im0s, c1,(c2[0]+c1[0], c2[1]+c1[1]),(255,255,255),2)\n                            \n        \n        result={'image_id': image_id, \"PredictionString\": \" \".join(box_scores)} \n        fig = plt.figure(figsize=(50, 50))\n        a = fig.add_subplot(1, 4, 1)\n        imgplot = plt.imshow(im0s)\n  \n\n        # all_path.append(path)\n        # final_conf_bbox.append(box_scores)  \n        results.append(result)\n \n    return results\n\n\nif __name__ == '__main__':\n    class opt:\n        weights = \"/kaggle/input/yolo-new-ss/best_yolov5SS149_wheat.pt\"\n        img_size = 1024\n        conf_thres = 0.3\n        iou_thres = 0.5\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":{},"cell_type":"markdown","source":"# metadata submission","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df = pd.DataFrame(res, columns=['image_id', 'PredictionString'])\nprint(test_df)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.to_csv(\"/kaggle/working/submission.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Thanks for reading my notebook :D ","execution_count":null}],"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}