{"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\nimport os\nfor 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\nfrom keras.models import Sequential\nimport keras\nimport tensorflow as tf\nfrom keras.layers import Input,Dense,Activation,ZeroPadding2D,BatchNormalization,Flatten,Conv2D,MaxPool2D,Dropout,Reshape,Add\nfrom keras.layers import LeakyReLU\nfrom keras.models import Model\nimport keras.backend as K\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.models import load_model\nimport cv2\nimport pandas as pd","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def yolo_loss(y_true,y_pred):\n  lossx=K.sum(tf.math.multiply(K.square(y_true[:,:,:,0:1]-y_pred[:,:,:,0:1]),y_true[:,:,:,4:]),axis=[1,2,3])\n  lossy=K.sum(tf.math.multiply(K.square(y_true[:,:,:,1:2]-y_pred[:,:,:,1:2]),y_true[:,:,:,4:]),axis=[1,2,3])\n  loss1=lossx+lossy\n  lossw=K.sum(tf.math.multiply(K.square(y_true[:,:,:,2:3]-y_pred[:,:,:,2:3]),y_true[:,:,:,4:]),axis=[1,2,3])\n  lossh=K.sum(tf.math.multiply(K.square(y_true[:,:,:,3:4]-y_pred[:,:,:,3:4]),y_true[:,:,:,4:]),axis=[1,2,3])\n  loss2=lossw+lossh\n  loss_xy_wh=loss1+loss2\n  lossC=K.sum(tf.math.multiply(K.square(tf.math.subtract(y_true[:,:,:,4:],y_pred[:,:,:,4:])),y_true[:,:,:,4:]),axis=[1,2,3])\n  lossC2 =K.sum(tf.math.multiply(K.square(tf.math.subtract(y_true[:,:,:,4:],y_pred[:,:,:,4:])),(1-y_true[:,:,:,4:])),axis=[1,2,3])/16  \n  lossC=lossC+lossC2\n    \n  total_loss=loss_xy_wh+lossC\n  return total_loss","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"yolov3=load_model(\"../input/trained-yolov3-model/yolov3_keras_more_epochs.hdf5\",custom_objects={'yolo_loss':yolo_loss})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_list=['../input/global-wheat-detection/test/2fd875eaa.jpg','../input/global-wheat-detection/test/348a992bb.jpg','../input/global-wheat-detection/test/51b3e36ab.jpg','../input/global-wheat-detection/test/51f1be19e.jpg','../input/global-wheat-detection/test/53f253011.jpg','../input/global-wheat-detection/test/796707dd7.jpg','../input/global-wheat-detection/test/aac893a91.jpg','../input/global-wheat-detection/test/cb8d261a3.jpg','../input/global-wheat-detection/test/cc3532ff6.jpg','../input/global-wheat-detection/test/f5a1f0358.jpg','../input/no-box-image/00b5c6764.jpg']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"DIR_INPUT = '/kaggle/input/global-wheat-detection'\nDIR_TRAIN = f'{DIR_INPUT}/train'\nDIR_TEST = f'{DIR_INPUT}/test'\n\n\nimagenames = os.listdir(DIR_TEST)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results=[]\nfor count, name in enumerate(imagenames):\n    ids = name.split('.')[0]\n    imagepath = '%s/%s.jpg'%(DIR_TEST,ids)\n    img=cv2.imread(imagepath)\n    test_img=cv2.resize(img,(256,256))\n    test_img=test_img/255.0\n    test_img=test_img[np.newaxis,:]\n    test_box=yolov3.predict(test_img)\n    box=test_box[0]\n    img=cv2.resize(img,(256,256))\n    pred_strings = []\n\n    for i in range(16):\n        for j in range(16):\n            if(box[i][j][4]>0.8):\n                x=(i*64)+(box[i][j][0]*64)\n                y=(j*64)+(box[i][j][1]*64)\n                w=box[i][j][2]*1024\n                h=box[i][j][3]*1024\n                x1=int((x-w/2)/4)\n                y1=int((y-h/2)/4)\n                x2=int((x+w/2)/4)\n                y2=int((y+h/2)/4)\n                #print(np.around(box[i][j][4],2),np.around(x1*4),np.around(y1*4),int(np.around(w)),int(np.around(h)) ,)\n                #cv2.rectangle(img,(x1,y1),(x2,y2),(255,0,255),1)\n                pred_strings.append(\"{0:.4f} {1} {2} {3} {4}\".format(np.clip(np.around(box[i][j][4],4),0,1), np.clip(int(np.around(x1*4)),0,1023), np.clip(int(np.around(y1*4)),0,1023), np.clip(int(np.around(w)),0,1023), np.clip(int(np.around(h)),0,1023)))\n                #pred=pred+str(np.clip(np.around(box[i][j][4],4),0,1))+' '+str(np.clip(int(np.around(x1*4)),0,1023))+' '+str(np.clip(int(np.around(y1*4)),0,1023))+' '+str(np.clip(int(np.around(w)),0,1023))+' '+str(np.clip(int(np.around(h)),0,1023))+' '\n\n    if(len(pred_strings)>0):\n        result = {'image_id':ids,'PredictionString': \" \".join(pred_strings)}\n    else:\n        result = {'image_id':ids,'PredictionString': \" \"}\n        \n    results.append(result)\n    #prediction_dict[address[37:46]]=pred[:-1]\n      #cv2.imwrite('/content/test.jpg',img)\n    #plt.imshow(img[:,:,[2,1,0]])  \n    #fig=plt.gcf()\n    #fig.set_size_inches((12,12))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.to_csv('submission.csv', index=False)","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}