{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":18294,"databundleVersionId":1026537,"sourceType":"competition"},{"sourceId":8630423,"sourceType":"datasetVersion","datasetId":5167498}],"dockerImageVersionId":30445,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# UAS ADTT KELOMPOK 11 PART 2\n# Kelompok 11\n\n1. Jasmine Husna Sanditya (2006571034)\n2. Muhammad Jauhar Hakim (2006463982)\n3. Yudistira Dwi Cahya (2006530492)","metadata":{}},{"cell_type":"markdown","source":"# Code and Data Reference\n* https://www.kaggle.com/code/anmolys/animal-detection-using-yolo-v8/notebook\n* https://www.kaggle.com/competitions/iwildcam-2020-fgvc7\n* https://github.com/microsoft/CameraTraps/blob/main/megadetector.md","metadata":{}},{"cell_type":"markdown","source":"# Import Library and Data","metadata":{}},{"cell_type":"markdown","source":"# Part 1 :\nAnimal Detection in African Wildlife (Buffalo, Elephant, Rhino, and Zebra)\n\nhttps://www.kaggle.com/code/hakim571/uas-adtt-kelompok-12-part-1\n\n# Part 2 :\nAnimal Detection in Wildlife Across the World\n\nhttps://www.kaggle.com/code/hakim571/uas-adtt-kelompok-12-part-2","metadata":{}},{"cell_type":"code","source":"!apt-get update\n!apt install -y python3.8","metadata":{"execution":{"iopub.status.busy":"2024-06-07T10:37:56.979837Z","iopub.execute_input":"2024-06-07T10:37:56.980328Z","iopub.status.idle":"2024-06-07T10:38:18.068415Z","shell.execute_reply.started":"2024-06-07T10:37:56.980283Z","shell.execute_reply":"2024-06-07T10:38:18.066725Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install virtualenv\n\n%cd /kaggle/working\n!virtualenv venv -p $(which python3.8)\n# !virtualenv myenv","metadata":{"execution":{"iopub.status.busy":"2024-06-07T10:38:18.070914Z","iopub.execute_input":"2024-06-07T10:38:18.071376Z","iopub.status.idle":"2024-06-07T10:38:36.628984Z","shell.execute_reply.started":"2024-06-07T10:38:18.071333Z","shell.execute_reply":"2024-06-07T10:38:36.627475Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!python3.8 --version","metadata":{"execution":{"iopub.status.busy":"2024-06-07T10:38:36.631058Z","iopub.execute_input":"2024-06-07T10:38:36.631573Z","iopub.status.idle":"2024-06-07T10:38:37.733991Z","shell.execute_reply.started":"2024-06-07T10:38:36.631520Z","shell.execute_reply":"2024-06-07T10:38:37.732510Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!/kaggle/working/venv/bin/pip install torch==1.10.1","metadata":{"execution":{"iopub.status.busy":"2024-06-07T10:39:49.713373Z","iopub.execute_input":"2024-06-07T10:39:49.713889Z","iopub.status.idle":"2024-06-07T10:40:36.708528Z","shell.execute_reply.started":"2024-06-07T10:39:49.713843Z","shell.execute_reply":"2024-06-07T10:40:36.705066Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!/kaggle/working/venv/bin/pip install PytorchWildlife","metadata":{"execution":{"iopub.status.busy":"2024-06-07T10:40:36.713807Z","iopub.execute_input":"2024-06-07T10:40:36.714468Z","iopub.status.idle":"2024-06-07T10:42:08.107937Z","shell.execute_reply.started":"2024-06-07T10:40:36.714405Z","shell.execute_reply":"2024-06-07T10:42:08.105838Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Exploring IWildCam 2020 Data","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nfrom PIL import Image\nimport glob \nimport matplotlib.pyplot as plt\nimport json\nimport os\nos.listdir('/kaggle/input/iwildcam-2020-fgvc7')","metadata":{"execution":{"iopub.status.busy":"2024-06-07T14:35:04.498569Z","iopub.execute_input":"2024-06-07T14:35:04.499999Z","iopub.status.idle":"2024-06-07T14:35:04.515739Z","shell.execute_reply.started":"2024-06-07T14:35:04.499943Z","shell.execute_reply":"2024-06-07T14:35:04.514134Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_jpeg = glob.glob('../input/iwildcam-2020-fgvc7/train/*')\ntest_jpeg = glob.glob('../input/iwildcam-2020-fgvc7/test/*')\n\nprint(\"number of train jpeg data:\", len(train_jpeg))\nprint(\"number of test jpeg data:\", len(test_jpeg))","metadata":{"execution":{"iopub.status.busy":"2024-06-07T14:35:05.627947Z","iopub.execute_input":"2024-06-07T14:35:05.628934Z","iopub.status.idle":"2024-06-07T14:35:09.974510Z","shell.execute_reply.started":"2024-06-07T14:35:05.628879Z","shell.execute_reply":"2024-06-07T14:35:09.973052Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig = plt.figure(figsize=(25, 16))\nfor i,im_path in enumerate(train_jpeg[:16]):\n    ax = fig.add_subplot(4, 4, i+1, xticks=[], yticks=[])\n    im = Image.open(im_path)\n    im = im.resize((480,270))\n    plt.imshow(im)","metadata":{"execution":{"iopub.status.busy":"2024-06-07T14:35:09.976607Z","iopub.execute_input":"2024-06-07T14:35:09.976992Z","iopub.status.idle":"2024-06-07T14:35:13.711993Z","shell.execute_reply.started":"2024-06-07T14:35:09.976954Z","shell.execute_reply":"2024-06-07T14:35:13.709958Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Running MegaDetector Pytorch","metadata":{}},{"cell_type":"code","source":"from IPython.display import Image\nImage(\"/kaggle/input/zoo1235/86760c00-21bc-11ea-a13a-137349068a90.jpg\")","metadata":{"execution":{"iopub.status.busy":"2024-06-07T11:21:54.994868Z","iopub.execute_input":"2024-06-07T11:21:54.996099Z","iopub.status.idle":"2024-06-07T11:21:55.016772Z","shell.execute_reply.started":"2024-06-07T11:21:54.996047Z","shell.execute_reply":"2024-06-07T11:21:55.015458Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%writefile /kaggle/working/test.py\n\nimport torch\nfrom PytorchWildlife.models import detection as pw_detection\nfrom PytorchWildlife.models import classification as pw_classification\nfrom PytorchWildlife import utils as pw_utils\nfrom PytorchWildlife.data import transforms as pw_trans\nimport os\nimport numpy as np\nfrom PIL import Image\n\nimg = torch.randn((3, 1280, 1280))\n\n# Detection\ndetection_model = pw_detection.MegaDetectorV5() # Model weights are automatically downloaded.\ndetection_result = detection_model.single_image_detection(img)\n\n#Classification\nclassification_model = pw_classification.AI4GAmazonRainforest() # Model weights are automatically downloaded.\nclassification_results = classification_model.single_image_classification(img)\n\ntgt_img_path = \"/kaggle/input/zoo1235/86760c00-21bc-11ea-a13a-137349068a90.jpg\"\ntemp_file_path = \"/kaggle/working/\"\nimg = np.array(Image.open(tgt_img_path).convert(\"RGB\"))\ntransform = pw_trans.MegaDetector_v5_Transform(target_size=detection_model.IMAGE_SIZE,\n                                               stride=detection_model.STRIDE)\nresults = detection_model.single_image_detection(transform(img), img.shape, tgt_img_path)\npw_utils.save_detection_images(results, os.path.join(\".\",\"demo_output\"), overwrite=False)\nprint(results)","metadata":{"execution":{"iopub.status.busy":"2024-06-07T15:02:39.421373Z","iopub.execute_input":"2024-06-07T15:02:39.421897Z","iopub.status.idle":"2024-06-07T15:02:39.432392Z","shell.execute_reply.started":"2024-06-07T15:02:39.421855Z","shell.execute_reply":"2024-06-07T15:02:39.430670Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!/kaggle/working/venv/bin/python3.8 /kaggle/working/test.py","metadata":{"execution":{"iopub.status.busy":"2024-06-07T15:02:40.364016Z","iopub.execute_input":"2024-06-07T15:02:40.364471Z","iopub.status.idle":"2024-06-07T15:03:14.600312Z","shell.execute_reply.started":"2024-06-07T15:02:40.364431Z","shell.execute_reply":"2024-06-07T15:03:14.595087Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Image(\"/kaggle/working/demo_output/86760c00-21bc-11ea-a13a-137349068a90.jpg\")","metadata":{"execution":{"iopub.status.busy":"2024-06-07T13:57:28.704442Z","iopub.execute_input":"2024-06-07T13:57:28.705013Z","iopub.status.idle":"2024-06-07T13:57:28.727529Z","shell.execute_reply.started":"2024-06-07T13:57:28.704952Z","shell.execute_reply":"2024-06-07T13:57:28.726077Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# x1, y1,w_box, h_box = results[0]['detections'][0][\"bbox\"]\n# ymin,xmin,ymax, xmax = y1, x1, y1+h_box, x1+w_box\nimport PIL\nimport matplotlib.pyplot as plt\nimg2 = PIL.Image.open(\"/kaggle/input/zoo1235/86760c00-21bc-11ea-a13a-137349068a90.jpg\")\nxmin,ymin,xmax, ymax = 1099, 581,1282,701\nbbox1 = [xmin,ymin,xmax, ymax]\narea = (xmin, ymin, xmax,ymax)\nout = img2.crop(area)\nplt.imshow(out)","metadata":{"execution":{"iopub.status.busy":"2024-06-07T11:45:20.446100Z","iopub.execute_input":"2024-06-07T11:45:20.446667Z","iopub.status.idle":"2024-06-07T11:45:20.793369Z","shell.execute_reply.started":"2024-06-07T11:45:20.446549Z","shell.execute_reply":"2024-06-07T11:45:20.791884Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import cv2\nfrom matplotlib import pyplot as plt\n\nimport albumentations as A\n\nBOX_COLOR = (255, 0, 0) # Red\nTEXT_COLOR = (255,255,255) # White\n\n\ndef visualize_bbox(img, bbox, class_name, color=BOX_COLOR, thickness=2):\n    \"\"\"Visualizes a single bounding box on the image\"\"\"\n    w=bbox[2]-bbox[0]\n    h=bbox[3]-bbox[1]\n    x_min = bbox[0]\n    y_min = bbox[1]\n    x_min, x_max, y_min, y_max = int(x_min), int(x_min + w), int(y_min), int(y_min + h)\n\n    cv2.rectangle(img, (x_min, y_min), (x_max, y_max), color=color, thickness=thickness)\n\n    ((text_width, text_height), _) = cv2.getTextSize(class_name, cv2.FONT_HERSHEY_SIMPLEX, 0.9, 3)\n    cv2.rectangle(img, (x_min, y_min - int(1.3 * text_height)), (x_min + text_width, y_min), BOX_COLOR, -1)\n    cv2.putText(\n        img,\n        text=class_name,\n        org=(x_min, y_min - int(0.3 * text_height)),\n        fontFace=cv2.FONT_HERSHEY_SIMPLEX,\n        fontScale=0.9,\n        color=TEXT_COLOR,\n        thickness = 2,\n        lineType=cv2.LINE_AA,\n    )\n    return img\n\n\ndef visualize(image, bboxes, category_name):\n    img = image.copy()\n    for bbox, category_id in zip(bboxes, category_ids):\n        class_name = category_id\n        img = visualize_bbox(img, bbox, class_name)\n    plt.figure(figsize=(12, 12))\n    plt.axis('off')\n    plt.imshow(img)\nimage = cv2.imread('/kaggle/input/zoo1235/86760c00-21bc-11ea-a13a-137349068a90.jpg')\nimage = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\nbboxes = [[1099, 581,1282,701]]\ncategory_ids = [\"Animal\"]\nvisualize(image, bboxes, category_ids)","metadata":{"execution":{"iopub.status.busy":"2024-06-07T13:57:28.729401Z","iopub.execute_input":"2024-06-07T13:57:28.729860Z","iopub.status.idle":"2024-06-07T13:57:29.742778Z","shell.execute_reply.started":"2024-06-07T13:57:28.729813Z","shell.execute_reply":"2024-06-07T13:57:29.741417Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%writefile /kaggle/working/test2.py\n\nimport torch\nimport cv2\nfrom PytorchWildlife.models import detection as pw_detection\nfrom PytorchWildlife.models import classification as pw_classification\nfrom PytorchWildlife import utils as pw_utils\nfrom PytorchWildlife.data import transforms as pw_trans\nimport os\nimport numpy as np\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport glob\nimport random\n\n# Detection\ndetection_model = pw_detection.MegaDetectorV5() # Model weights are automatically downloaded.\ntrain_jpeg = glob.glob('../input/iwildcam-2020-fgvc7/train/*')\nrandom.seed(10)\n\nfor i in range(16):    \n    tgt_img_path = random.choice(train_jpeg)\n    temp_file_path = \"/kaggle/working/\"\n    img = np.array(Image.open(tgt_img_path).convert(\"RGB\"))\n    transform = pw_trans.MegaDetector_v5_Transform(target_size=detection_model.IMAGE_SIZE,\n                                                   stride=detection_model.STRIDE)\n    results = detection_model.single_image_detection(transform(img), img.shape, tgt_img_path)\n    pw_utils.save_detection_images(results, os.path.join(\".\",\"demo_folder\"), overwrite=False)","metadata":{"execution":{"iopub.status.busy":"2024-06-07T15:05:54.251791Z","iopub.execute_input":"2024-06-07T15:05:54.252330Z","iopub.status.idle":"2024-06-07T15:05:54.263221Z","shell.execute_reply.started":"2024-06-07T15:05:54.252281Z","shell.execute_reply":"2024-06-07T15:05:54.261542Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!/kaggle/working/venv/bin/python3.8 /kaggle/working/test2.py","metadata":{"execution":{"iopub.status.busy":"2024-06-07T15:05:54.806047Z","iopub.execute_input":"2024-06-07T15:05:54.806610Z","iopub.status.idle":"2024-06-07T15:08:18.466703Z","shell.execute_reply.started":"2024-06-07T15:05:54.806502Z","shell.execute_reply":"2024-06-07T15:08:18.464798Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"out_folder = glob.glob('/kaggle/working/demo_folder/*')\nfig = plt.figure(figsize=(25, 16))\nfor i in range(16):\n    ax = fig.add_subplot(4, 4, i+1, xticks=[], yticks=[])\n    im = PIL.Image.open(out_folder[i])\n    im = im.resize((480,270))\n    plt.imshow(im)","metadata":{"execution":{"iopub.status.busy":"2024-06-07T15:22:22.789840Z","iopub.execute_input":"2024-06-07T15:22:22.790386Z","iopub.status.idle":"2024-06-07T15:22:26.114698Z","shell.execute_reply.started":"2024-06-07T15:22:22.790335Z","shell.execute_reply":"2024-06-07T15:22:26.112665Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%writefile /kaggle/working/test3.py\n\nimport torch\nimport cv2\nfrom PytorchWildlife.models import detection as pw_detection\nfrom PytorchWildlife.models import classification as pw_classification\nfrom PytorchWildlife import utils as pw_utils\nfrom PytorchWildlife.data import transforms as pw_trans\nimport os\nimport numpy as np\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport glob\nimport random\n\n# Detection\ndetection_model = pw_detection.MegaDetectorV5() # Model weights are automatically downloaded.\ntrain_jpeg = glob.glob('../input/iwildcam-2020-fgvc7/train/*')\nrandom.seed(13)\n\nfor i in range(16):    \n    tgt_img_path = random.choice(train_jpeg)\n    temp_file_path = \"/kaggle/working/\"\n    img = np.array(Image.open(tgt_img_path).convert(\"RGB\"))\n    transform = pw_trans.MegaDetector_v5_Transform(target_size=detection_model.IMAGE_SIZE,\n                                                   stride=detection_model.STRIDE)\n    results = detection_model.single_image_detection(transform(img), img.shape, tgt_img_path)\n    pw_utils.save_detection_images(results, os.path.join(\".\",\"demo_folder2\"), overwrite=False)","metadata":{"execution":{"iopub.status.busy":"2024-06-07T15:26:59.529692Z","iopub.execute_input":"2024-06-07T15:26:59.530226Z","iopub.status.idle":"2024-06-07T15:26:59.540463Z","shell.execute_reply.started":"2024-06-07T15:26:59.530182Z","shell.execute_reply":"2024-06-07T15:26:59.538845Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!/kaggle/working/venv/bin/python3.8 /kaggle/working/test3.py","metadata":{"execution":{"iopub.status.busy":"2024-06-07T15:27:07.385986Z","iopub.execute_input":"2024-06-07T15:27:07.386495Z","iopub.status.idle":"2024-06-07T15:29:33.606233Z","shell.execute_reply.started":"2024-06-07T15:27:07.386446Z","shell.execute_reply":"2024-06-07T15:29:33.604446Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"out_folder = glob.glob('/kaggle/working/demo_folder2/*')\nfig = plt.figure(figsize=(25, 16))\nfor i in range(16):\n    ax = fig.add_subplot(4, 4, i+1, xticks=[], yticks=[])\n    im = PIL.Image.open(out_folder[i])\n    im = im.resize((480,270))\n    plt.imshow(im)","metadata":{"execution":{"iopub.status.busy":"2024-06-07T15:29:33.609031Z","iopub.execute_input":"2024-06-07T15:29:33.609500Z","iopub.status.idle":"2024-06-07T15:29:37.159007Z","shell.execute_reply.started":"2024-06-07T15:29:33.609455Z","shell.execute_reply":"2024-06-07T15:29:37.157051Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}