{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\n# import os\n# for dirname, _, filenames in os.walk('/kaggle/input'):\n#     for filename in filenames:\n# #         print(os.path.join(dirname, filename))\n\n# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\nimport time\nimport cv2\nimport os\n\n\n\ndef load_network(weightsPath, configPath):\n\n    print(\"[INFO] loading YOLO from disk...\")\n    net = cv2.dnn.readNetFromDarknet(configPath, weightsPath)\n    return net\n\ndef get_predictions(labelsPath,img, net):\n  \n    LABELS = open(labelsPath).read().strip().split(\"\\n\")\n\n\n    a=0\n    image = img\n    (H, W) = image.shape[:2]\n\n    # determine only the *output* layer names that we need from YOLO\n    ln = net.getLayerNames()\n    ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]\n\n    # construct a blob from the input image and then perform a forward\n    # pass of the YOLO object detector, giving us our bounding boxes and\n    # associated probabilities\n    blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416),\n    swapRB=True, crop=False)\n    net.setInput(blob)\n    start = time.time()\n    layerOutputs = net.forward(ln)\n    end = time.time()\n\n    # show timing information on YOLO\n    #   print(\"[INFO] YOLO took {:.6f} seconds\".format(end - start))\n\n\n    # initialize our lists of detected bounding boxes, confidences, and\n    # class IDs, respectively\n    boxes = []\n    confidences = []\n    classIDs = []\n\n\n    # loop over each of the layer outputs\n    for output in layerOutputs:\n        # loop over each of the detections\n        for detection in output:\n            \n            \n          # extract the class ID and confidence (i.e., probability) of\n          # the current object detection\n            scores = detection[5:]\n            classID = np.argmax(scores)\n            confidence = scores[classID]\n\n          # filter out weak predictions by ensuring the detected\n          # probability is greater than the minimum probability\n            if confidence > 0.5:\n                # scale the bounding box coordinates back relative to the\n                # size of the image, keeping in mind that YOLO actually\n                # returns the center (x, y)-coordinates of the bounding\n                # box followed by the boxes' width and height\n                box = detection[0:4] * np.array([W, H, W, H])\n                (centerX, centerY, width, height) = box.astype(\"int\")\n\n                # use the center (x, y)-coordinates to derive the top and\n                # and left corner of the bounding box\n                x = int(centerX - (width / 2))\n                y = int(centerY - (height / 2))\n\n                # update our list of bounding box coordinates, confidences,\n                # and class IDs\n                boxes.append([x, y, int(width), int(height)])\n                confidences.append(float(confidence))\n                classIDs.append(classID)\n\n        idxs = cv2.dnn.NMSBoxes(boxes, confidences, 0.5,0.5)\n\n\n        cords=[]\n        find_labels=[]\n        # ensure at least one detection exists\n\n\n\n    if len(idxs)>0:\n        \n        # loop over the indexes we are keepin\n        for i in idxs.flatten():\n            \n\n            (x,y)=(boxes[i][0], boxes[i][1])\n            (w,h)=(boxes[i][2], boxes[i][3])\n            score=confidences[i]\n\n            text = \"{}:{:.2f}\".format(LABELS[classIDs[i]],score)\n            a,b=x,y\n            c,d=x+w, y+h\n\n            cords.append(\"{:.2f} {} {} {} {}\".format(score,abs(int(a)),abs(int(b)),abs(int(w)),abs(int(h))))\n\n\n            cv2.rectangle(image, (a,b),(c,d),(255,0,0),2)\n            cv2.putText(image, text, (a, b - 5), cv2.FONT_HERSHEY_SIMPLEX,1, (255,255,0), 3)\n            find_labels.append(text)\n\n        return image,find_labels,cords\n\n    else:\n\n        return [],[],[]\n      \n\n\nnet=load_network(\"../input/trained-weights-and-cfg/yolov3_2000.weights\", \"../input/trained-weights-and-cfg/yolov3.cfg\")\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"from tqdm import tqdm\nimport cv2\nimport matplotlib.pyplot as plt\n\ndata_dir = '../input/global-wheat-detection/test'\n\nsubmission = pd.read_csv('../input/global-wheat-detection/sample_submission.csv')\n\n\nroot_image = \"../input/global-wheat-detection/test/\"\ntest_images = [root_image + f\"{img}.jpg\" for img in submission.image_id]\n\n\nsubmission = []\n\nfor imagepath in test_images:\n    im=cv2.imread(imagepath)\n    image, labels , cords= get_predictions(\"../input/trained-weights-and-cfg/labels.name\",im,net)\n    prediction_string = \" \".join(cords)\n#     plt.figure(figsize=(10,10))\n#     plt.imshow(image)\n#     plt.show()\n    \n    submission.append([os.path.basename(imagepath)[:-4],prediction_string])\n\nsample_submission = pd.DataFrame(submission, columns=[\"image_id\",\"PredictionString\"])\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission.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}