{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport cv2\nimport torch\nimport csv\nimport os\nimport sys\n\nsys.path.insert(0, \"/kaggle/input/yolov3\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from models import *\nfrom utils.datasets import *\nfrom utils.utils import *\n\nimport csv\n\nimport torch\nimport torch.backends.cudnn as cudnn\nimport torch.nn as nn\nimport torch.nn.functional as F\n\ninference_size = 512\n\ndevice = torch.device('cuda:0')\n\nmodel = Darknet('/kaggle/input/yolov3/yolov3-spp-customanchor.cfg', inference_size)\nmodel.load_state_dict(torch.load('/kaggle/input/yolov3/best.pt', map_location=device)['model'])\nmodel.to(device).eval()\n\nimg_paths = os.listdir(\"/kaggle/input/global-wheat-detection/test/\")\nimg_paths = [os.path.join(\"/kaggle/input/global-wheat-detection/test/\", img_path) for img_path in img_paths]\n\nimg = torch.zeros((1, 3, inference_size, inference_size), device=device)  # init img\n_ = model(img.float())\n\nf = open('/kaggle/working/submission.csv','w',encoding='utf-8', newline='')\ncsv_writer = csv.writer(f)\ncsv_writer.writerow([\"image_id\", \"PredictionString\"])\n\ndataset = LoadImages(\"/kaggle/input/global-wheat-detection/test/\", img_size=inference_size)\nfor path, img, im0s, _ in dataset:\n    img = torch.from_numpy(img).to(device)\n    img = img.float() / 255.0\n    img = img.unsqueeze(0)\n\n    pred = model(img, False)[0]\n    pred = non_max_suppression(pred, 0.3, 0.6, multi_label=False, classes=None, agnostic=False)\n\n    li = []\n    for i, det in enumerate(pred):  # detections for image i\n        if det is not None and len(det):\n            det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0s.shape).round()\n            for *xyxy, conf, cls in det:\n                li += [float(conf), int(xyxy[0]), int(xyxy[1]), int(xyxy[2] - xyxy[0]), int(xyxy[3] - xyxy[1])]\n            \n    string = ' '.join([str(v) for v in li])\n    print(path)\n    csv_writer.writerow([os.path.basename(path)[0:-4], string])  \n'''\nfor img_path in img_paths:\n    img0 = cv2.imread(img_path)  # BGR\n    img = letterbox(img0, new_shape=inference_size)[0]\n    img = img[:, :, ::-1].transpose(2, 0, 1)  # BGR to RGB, to 3x416x416\n    img = np.ascontiguousarray(img)\n    \n    img = torch.from_numpy(img).to(device)\n    img = img.float()\n    img /= 255.0  # 0 - 255 to 0.0 - 1.0\n    if img.ndimension() == 3:\n        img = img.unsqueeze(0)\n        \n    pred = model(img, False)[0]\n    pred = non_max_suppression(pred, 0.3, 0.6, multi_label=False, classes=None, agnostic=False)\n    \n    li = []\n    for i, det in enumerate(pred):  # detections for image i\n        det[:, :4] = scale_coords(img.shape[2:], det[:, :4], img0.shape).round()\n        for *xyxy, conf, cls in det:\n            li += [float(conf), int(xyxy[0]), int(xyxy[1]), int(xyxy[2] - xyxy[0]), int(xyxy[3] - xyxy[1])]\n            \n    string = ' '.join([str(v) for v in li])\n    csv_writer.writerow([os.path.basename(img_path)[0:-4], string])\n'''\n\nf.close()","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}