{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":67836,"databundleVersionId":7527339,"sourceType":"competition"}],"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"#### This notebook was inspired from [medium](https://medium.com/)###and [here](https://www.kaggle.com/code/ammarnassanalhajali/layout-parser-model-training) ##and [here](https://www.kaggle.com/code/salmankhondker/starter-notebook-dl-sprint-2-0)##and [here](https://www.kaggle.com/code/ataullhasaim/mws-dl-enigma-1-0-starter-notebook)","metadata":{}},{"cell_type":"code","source":"!python -m pip install 'git+https://github.com/facebookresearch/detectron2.git'","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import detectron2\nfrom detectron2.utils.logger import setup_logger\nsetup_logger()\nfrom detectron2 import model_zoo\nfrom detectron2.engine import DefaultTrainer\nfrom detectron2.engine import DefaultPredictor\nfrom detectron2.config import get_cfg\nfrom detectron2.utils.visualizer import Visualizer\nfrom detectron2.structures import BoxMode\nfrom detectron2.data import DatasetCatalog, MetadataCatalog\nfrom detectron2.evaluation import COCOEvaluator, inference_on_dataset, LVISEvaluator\nfrom detectron2.data import build_detection_test_loader\nfrom detectron2.utils.visualizer import ColorMode\n\n# other libs (other necessary imports in Colab file to make the list shorter here)\n\nimport torch, torchvision\nimport torchvision.transforms as transforms\nfrom pathlib import Path\nimport os\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\nimport pandas as pd\nimport cv2","metadata":{"execution":{"iopub.status.busy":"2024-02-08T08:46:22.196856Z","iopub.execute_input":"2024-02-08T08:46:22.197302Z","iopub.status.idle":"2024-02-08T08:46:27.961513Z","shell.execute_reply.started":"2024-02-08T08:46:22.197261Z","shell.execute_reply":"2024-02-08T08:46:27.960513Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cfg = get_cfg()\ncfg.merge_from_file(model_zoo.get_config_file(\"COCO-Detection/faster_rcnn_R_50_FPN_3x.yaml\"))\ncfg.MODEL.DEVICE = 'cuda' # cuda\ncfg.MODEL.ROI_HEADS.NUM_CLASSES = 13\ncfg.MODEL.WEIGHTS = \"model_final.pth\"\ncfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5   # set the testing threshold for this model\npredictor = DefaultPredictor(cfg)\n\nim = cv2.imread(\"/kaggle/input/1st-image-in-test/chittagong_bohoddarhat1_1003.jpg\")\noutputs = predictor(im)\nv = Visualizer(im, scale=1., instance_mode =  ColorMode.IMAGE    )\n\nv = v.draw_instance_predictions(outputs[\"instances\"].to(\"cpu\"))\nimg = v.get_image()[:,:,[2,1,0]]\nimg = Image.fromarray(img)\nplt.figure(figsize=(10, 10))\nplt.imshow(img)","metadata":{"execution":{"iopub.status.busy":"2024-02-08T08:46:27.962871Z","iopub.execute_input":"2024-02-08T08:46:27.963413Z","iopub.status.idle":"2024-02-08T08:46:35.762760Z","shell.execute_reply.started":"2024-02-08T08:46:27.963379Z","shell.execute_reply":"2024-02-08T08:46:35.761792Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_prediction_string(boxes, scores, classes,height1, width1):\n    pred_strs = []\n    for i, score in enumerate(scores):\n        single_pred_str = \"\"\n        single_pred_str += str(float(classes[i])) + \" \" + str(float(score)) + \" \"\n        #print(boxes[i])\n        x_center , y_center, width,height = boxes[i]\n        x1 = ((float(x_center) + float(width))/2)/float(width1)\n        y1 = ((float(y_center) + float(height))/2)/float(height1)\n        \n        width = (-float(x_center) + float(width))/float(width1)\n        height = (-float(y_center) + float(height))/float(height1)\n        x2=float(x1)-(float(width)/2)\n        y2=float(y1)-(float(height)/2)\n        #single_pred_str += \" \".join(str(float(x)) for x in boxes[i])\n        single_pred_str +=  f\"{x2} {y2} {width} {height}\"\n        \n        pred_strs.append(single_pred_str)\n    ans = ','.join(map(str, pred_strs))\n    if len(ans):\n        return ans\n#     the solution metrics faield in case of a NaN, '' (empty). So, return \"0 0 0 0 0 0\" for NaN, '' (empty) string\n    return \"0 0 0 0 0 0\"\n\n# get the predcition in id, ImageID, PredictionString_pred foramt ...\n\ndef get_prediction_entry(i, filename, boxes, scores, classes,height1, width1):\n    return {\n        \"id\": i, # strating from 0 ...\n        \"ImageID\": filename.split('.')[0], # before the extension ...\n        \"PredictionString_pred\": get_prediction_string(boxes, scores, classes,height1, width1)\n    }\n\n# Directory path ...\ntest_directory = \"/kaggle/input/dl-enigma-10-sust-cse-carnival-2024/dlenigma1/BadODD/images/test\"\n#test_directory = \"/kaggle/input/image-test\"\n# Load the model ...\n#model = YOLO('/kaggle/working/runs/detect/train/weights/best.pt')\n\n# do the inference ...\n\ndef predict_all_files(test_directory):\n    predictions = []\n    for i,filename in tqdm(enumerate(os.listdir(test_directory))):\n        if filename.endswith(\".jpg\"):\n            filepath = os.path.join(test_directory, filename)\n            im = cv2.imread(filepath)\n            height1, width1, _ = im.shape\n            \n            #print(im.shape)\n            results = predictor(im)\n            instances = results[\"instances\"]\n            boxes_cpu = instances.pred_boxes.tensor.cpu()\n            scores_cpu = instances.scores.cpu()\n            classes_cpu = instances.pred_classes.cpu()\n\n                   # Convert CPU tensors to NumPy arrays\n            boxes = boxes_cpu.numpy()  # Extract bounding boxes as a numpy array\n            scores = scores_cpu.numpy()  # Extract prediction scores as a numpy array\n            classes = classes_cpu.numpy()\n            prediction = get_prediction_entry(i, filename, boxes, scores, classes,height1, width1)\n            predictions.append(prediction)\n            #print(predictions[0])\n            \n#             to csv format ...\n    predictions_df = pd.DataFrame(predictions)\n    predictions_df.to_csv(\"submission.csv\", index=False)\n\n# call the inference function ...\npredict_all_files(test_directory)","metadata":{"execution":{"iopub.status.busy":"2024-02-08T08:46:35.764714Z","iopub.execute_input":"2024-02-08T08:46:35.765103Z","iopub.status.idle":"2024-02-08T08:50:57.310195Z","shell.execute_reply.started":"2024-02-08T08:46:35.765069Z","shell.execute_reply":"2024-02-08T08:50:57.309128Z"},"trusted":true},"execution_count":null,"outputs":[]}]}