{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import os\nimport shutil\nimport pandas as pd\nimport numpy as np\nimport cv2\nimport glob\nimport time\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"photos = glob.glob('../input/global-wheat-detection/train/*.jpg')\nlen(photos)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df = pd.read_csv('../input/wheat-data/train_2.csv')\ndf.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(df['image_id'].unique())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df = pd.read_csv('../input/wheat-data/labels.csv')\ndf.head()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"full_path_to_csv = '../input/wheat-data'\nfull_path_to_train_images = '../input/global-wheat-detection/train'\nfull_path_to_test_images = '../input/global-wheat-detection/test'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"classes = pd.read_csv('../input/wheat-data/labels.csv',usecols=[0,1],header=None)\nclasses","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels = ['wheat']\nencrypted_strings = []\n\nfor v in labels:\n  sub_classes = classes.loc[classes[1]==v]\n  print(sub_classes)\n\n  e = sub_classes.iloc[0][0]\n  print(e)\n\n  encrypted_strings.append(e)\n\nprint()\nprint(labels)\nprint(encrypted_strings)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"annotations = pd.read_csv('../input/wheat-data/train_2.csv',usecols=['image_id',\n                                                                    'label_name',\n                                                                    'xmin',\n                                                                    'ymin',\n                                                                    'width.1',\n                                                                    'height.1'])\nannotations.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub_ann = annotations.loc[annotations['label_name'].isin(encrypted_strings)].copy()\nprint(sub_ann.head())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub_ann['class_number'] = ''\nsub_ann['center x'] = ''\nsub_ann['center y'] = ''\nsub_ann['xmax'] = ''\nsub_ann['ymax'] = ''\n\nfor i in range(len(encrypted_strings)):\n  sub_ann.loc[sub_ann['label_name']==encrypted_strings[i], 'class_number'] = i\n\nsub_ann['xmax'] = sub_ann['width.1'] + sub_ann['xmin']\nsub_ann['ymax'] = sub_ann['height.1'] + sub_ann['ymin']\n\nsub_ann['center x'] = (sub_ann['xmax']+sub_ann['xmin'])/2\nsub_ann['center y'] = (sub_ann['ymax']+sub_ann['ymin'])/2\n\nr = sub_ann.loc[:, ['image_id',\n                    'class_number',\n                    'center x',\n                    'center y',\n                    'width.1',\n                    'height.1']].copy()\nprint(r.head())\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pwd()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.chdir(full_path_to_train_images)\nprint(os.getcwd())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pwd()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cnt = 0\nfor current_dir, dirs, files in os.walk('.'):\n  for f in files:\n    if f.endswith('.jpg'):\n      image_name = f[:-4]\n\n      sub_r = r.loc[r['image_id'] == image_name]\n\n      resulted_frame = sub_r.loc[:,['class_number',\n                                    'center x',\n                                    'center y',\n                                    'width.1',\n                                    'height.1']].copy()\n\n      path_to_save = '/'+ image_name + '.txt'\n\n      resulted_frame.to_csv(path_to_save, header = False, index = False, sep=' ')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%cd ..","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%cd ..","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%cd ..","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%cd ..","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.chdir('kaggle/working')\nprint(os.getcwd())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test = glob.glob('../input/global-wheat-detection/test/*')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test[0][37:-4]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image = []\nstring = []\n\nfor i in range(len(test)):\n    img = test[i]\n    \n    image_BGR = cv2.imread(img)\n    image.append(str(img[37:-4]))\n    \n    #cv2.namedWindow('Original Image',cv2.WINDOW_NORMAL)\n    #cv2.imshow('Original Image',image_BGR)\n\n    #cv2.waitKey(0)\n\n    #cv2.destroyWindow('Original Image')\n\n    #check point\n    #print('Image Shape:',image_BGR.shape)\n\n    h,w = image_BGR.shape[:2]\n\n    #check point\n    #print(f'Image height {h} and width {w}')\n\n    blob = cv2.dnn.blobFromImage(image_BGR, 1/255, (416,416), swapRB =True, crop= False)\n\n    #check point\n    #print('Image shape: ',image_BGR.shape)\n    #print('Blob shape: ',blob.shape)\n\n    #check point\n    blob_to_show = blob[0,:,:,:].transpose(1,2,0)\n    #print('blob_to_show shape',blob_to_show.shape)\n\n    #cv2.namedWindow('Blob Image',cv2.WINDOW_NORMAL)\n\n    #cv2.imshow('Blob Image', cv2.cvtColor(blob_to_show , cv2.COLOR_RGB2BGR))\n    #cv2.waitKey(0)\n\n    #cv2.destroyWindow('Blob Image')\n\n    with open('../input/wheat-data/classes.names') as f:\n        labels = [line.strip() for line in f]\n\n    #print(List with labels names)    \n    #print(labels)\n\n    network = cv2.dnn.readNetFromDarknet('../input/wheat4/yolov3_custom_train.cfg',\n                                         '../input/wheat4/yolov3_custom_train_4000.weights')\n\n    #chech point\n    layers_names_all = network.getLayerNames()\n    #print(layers_names_all)\n\n    layers_names_output = [layers_names_all[i[0] - 1] for i in network.getUnconnectedOutLayers()]\n\n    #check points\n    #print(layers_names_output)\n\n    probability_minimum = 0.1\n\n    threshold = 0.5\n\n    colours = np.random.randint(0,255, size = (len(labels) ,3), dtype = 'uint8')\n\n    #check point\n    #print()\n    #print(type(colours))\n    #print(colours.shape)\n    #print(colours[0])\n\n    network.setInput(blob)\n    start = time.time()\n    output_from_network = network.forward(layers_names_output)\n    end = time.time()\n\n    #print(f'object detection took {end - start} seconds')\n\n\n    bounding_boxes = []\n    confidences = []\n    class_numbers = []\n\n    for result in output_from_network:\n        for detected_objects in result:\n            scores = detected_objects[5:]\n            \n            class_current = np.argmax(scores)\n            confidence_current = scores[class_current]\n        \n            #check point\n            #print(detected_objects.shape)\n        \n            if  confidence_current > probability_minimum:\n                box_current = detected_objects[0:4] * np.array([w,h,w,h])\n                x_center, y_center, box_width, box_height = box_current\n                x_min = int(x_center - (box_width/2))\n                y_min = int(y_center - (box_height/2))\n                \n                bounding_boxes.append([x_min, y_min, int(box_width), int(box_height)])\n                confidences.append(float(confidence_current))\n                class_numbers.append(class_current)\n            \n        \n\n        \n    result = cv2.dnn.NMSBoxes(bounding_boxes, confidences, probability_minimum, threshold)\n\n    pred_strings = []\n\n    counter = 1\n    if len(result)>0:\n    \n        for i in result.flatten():\n            #print(f'object {counter}: {labels[int(class_numbers[i])]}')\n            counter +=1\n        \n            x_min, y_min = bounding_boxes[i][0], bounding_boxes[i][1]\n        \n            box_width, box_height = bounding_boxes[i][2], bounding_boxes[i][3]\n        \n            colour_box_current = colours[class_numbers[i]].tolist()\n            #print(x_min, y_min, box_width, box_height)\n        \n            pred_strings.append(\"{0:.4f} {1} {2} {3} {4}\".format(confidences[i], x_min, y_min, box_width, box_height))\n            \n        \n            #check point\n            #print(type(colour_box_current)) List\n            #print(colour_box_current) [172,10,127]\n        \n            cv2.rectangle(image_BGR, (x_min,y_min),\n                         (x_min + box_width, y_min+box_height),\n                         colour_box_current,2)\n        \n            text_box_current = '{}: {:.4f}'.format(labels[int(class_numbers[i])],\n                                                  confidences[i])\n        \n            cv2.putText(image_BGR, text_box_current, (x_min, y_min-5),\n                       cv2.FONT_HERSHEY_COMPLEX, 0.7, colour_box_current, 2)\n    \n    pred_strings = str(pred_strings).replace(',','')\n    pred_strings = str(pred_strings).replace('[','')\n    pred_strings = str(pred_strings).replace(']','')\n    pred_strings = str(pred_strings).replace(\"'\",'')\n    string.append(pred_strings)\n\n    print()\n    print('Image:',img[16:])\n    print('Total objects been detected: ',len(bounding_boxes))\n    print('Number of objects left after non-maximum supprssion: ',counter-1)\n    #plt.show(image_BGR)\n\n\"\"\"\ncv2.namedWindow('Detections',cv2.WINDOW_NORMAL)\ncv2.imshow('Detections',image_BGR)\ncv2.waitKey(0)\ncv2.destroyWindow('Detections')\"\"\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df = pd.DataFrame()\ndf['image_id'] = image\ndf['PredictionString'] = string","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.to_csv('submission.csv',index = False)\ndf.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}