{"cells":[{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import numpy as np\nimport os\nimport cv2\nimport glob\nimport time\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\nimport seaborn as sns\nsns.set()\nimport pandas as pd\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"yolo_weights = '../input/yolo-trained-files/yolov3_wheat.weights'\n\nyolo_cfg='../input/yolo-trained-files/yolov3.cfg'\n\n# read class names from text file\nclasses = None\nwith open(\"../input/yolo-trained-files/classes.txt\", 'r') as f:\n    classes = [line.strip() for line in f.readlines()]\n\nCOLORS = np.random.uniform(0, 255, size=(len(classes), 3))\n\nnet = cv2.dnn.readNet(yolo_cfg,yolo_weights)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_output_layers(net):\n\n    layer_names = net.getLayerNames()\n\n    output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]\n\n    return output_layers\n\n\ndef imShow(image):\n\n  height, width = image.shape[:2]\n  resized_image = cv2.resize(image,(3*width, 3*height), interpolation = cv2.INTER_CUBIC)\n\n  fig = plt.gcf()\n  fig.set_size_inches(18, 10)\n  plt.axis(\"off\")\n  plt.imshow(cv2.cvtColor(resized_image, cv2.COLOR_BGR2RGB))\n  plt.show()\n\n\ndef draw_bounding_box(img,x, y, x_plus_w, y_plus_h):\n\n#     label = str(classes[class_id])\n\n#     color = COLORS[class_id]\n\n    cv2.rectangle(img, (x,y), (x_plus_w,y_plus_h), (0,0,255), 2)\n\n#     cv2.putText(img, label, (x+10,y+10), cv2.FONT_HERSHEY_SIMPLEX, 1, color, 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def yolo_detect(path_of_images):\n    image = cv2.imread(path_of_images)\n    try:\n        image.size == 0\n    except:\n        print('excepted image {}'.format(image))\n        return [\"No object detected and color detected \"]\n\n\n    Width = image.shape[1]\n    Height = image.shape[0]\n    scale = 0.00392\n    start1 = time.time()\n\n    blob = cv2.dnn.blobFromImage(image, scale, (608,608), (0,0,0), True, crop=False)\n\n    net.setInput(blob)\n\n\n\n    start2 = time.time()\n\n# run inference through the network\n# and gather predictions from output layers\n    outs = net.forward(get_output_layers(net))\n\n# initialization\n    class_ids = []\n    confidences = []\n    boxes = []\n    conf_threshold = 0.1\n    nms_threshold = 0.3\n# for each detetion from each output layer\n# get the confidence, class id, bounding box params\n# and ignore weak detections (confidence < 0.5)\n    for out in outs:\n        for detection in out:\n            scores = detection[5:]\n            class_id = np.argmax(scores)\n            confidence = scores[class_id]\n            if confidence > 0.5:\n                center_x = int(detection[0] * Width)\n                center_y = int(detection[1] * Height)\n                w = int(detection[2] * Width)\n                h = int(detection[3] * Height)\n                x = center_x - w / 2\n                y = center_y - h / 2\n                class_ids.append(class_id)\n                confidences.append(float(confidence))\n                boxes.append([x, y, w, h])\n    #arr=np.array([[0,0,0,0,0]])\n    #arr=np.ndarray.astype(arr,dtype='str',casting='unsafe')\n    obj_result = []\n\n# apply non-max suppression\n    indices = cv2.dnn.NMSBoxes(boxes, confidences, conf_threshold, nms_threshold)\n\n# go through the detections remaining\n# after nms and draw bounding box\n    for i in indices:\n        i = i[0]\n        box = boxes[i]\n        x = box[0]\n        y = box[1]\n        w = box[2]\n        h = box[3]\n\n        draw_bounding_box(image,round(x), round(y), round(x+w), round(y+h))\n\n\n\n        obj_result.append(\"{} {} {} {} {}\".format(round(confidences[i],2), round(x), round(y), round(w), round(h)))\n\n    imShow(image)\n\n    return \" \".join(obj_result)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nresults=[]\n\nfor i in glob.glob(\"../input/global-wheat-detection/test/*\"):\n    image_id = i.split(\"/\")[-1].split(\".\")[0]\n\n    key = image_id\n\n    res = yolo_detect(i)\n\n    result={'image_id': key, \"PredictionString\": res}\n\n    results.append(result)\n\n\n\n\ndf = pd.DataFrame(results,columns = ['image_id','PredictionString'])\n\ndf.to_csv(\"submission.csv\",index=False)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(df)","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}