{"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":"gpu","dataSources":[{"sourceId":19989,"databundleVersionId":1160143,"sourceType":"competition"}],"dockerImageVersionId":30699,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install torch torchvision\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-12-29T19:19:21.269868Z","iopub.execute_input":"2024-12-29T19:19:21.270435Z","iopub.status.idle":"2024-12-29T19:19:29.750207Z","shell.execute_reply.started":"2024-12-29T19:19:21.270406Z","shell.execute_reply":"2024-12-29T19:19:29.749108Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# important library:","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport os\nimport random\nfrom PIL import Image , ImageDraw \nfrom collections import Counter\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nimport torch\nimport torchvision\nfrom torchvision import transforms as T\n\nfrom torchvision.models.detection.faster_rcnn import FastRCNNPredictor\n\n","metadata":{"execution":{"iopub.status.busy":"2024-12-29T19:19:29.752249Z","iopub.execute_input":"2024-12-29T19:19:29.752958Z","iopub.status.idle":"2024-12-29T19:19:33.225887Z","shell.execute_reply.started":"2024-12-29T19:19:29.752921Z","shell.execute_reply":"2024-12-29T19:19:33.225151Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# load train data:","metadata":{}},{"cell_type":"code","source":"train = pd.read_csv(\"/kaggle/input/global-wheat-detection/train.csv\")\ntrain.head()","metadata":{"execution":{"iopub.status.busy":"2024-12-29T19:19:33.226962Z","iopub.execute_input":"2024-12-29T19:19:33.227340Z","iopub.status.idle":"2024-12-29T19:19:33.402991Z","shell.execute_reply.started":"2024-12-29T19:19:33.227315Z","shell.execute_reply":"2024-12-29T19:19:33.402115Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Split the bbox column to x1, y1, w, h ","metadata":{}},{"cell_type":"code","source":"coord = pd.DataFrame(list(train.bbox.apply(lambda x : x[1:-1].split(\",\")).values),columns=[\"x1\",\"y1\",\"w\",\"h\"])","metadata":{"execution":{"iopub.status.busy":"2024-12-29T19:19:33.404774Z","iopub.execute_input":"2024-12-29T19:19:33.405045Z","iopub.status.idle":"2024-12-29T19:19:33.727959Z","shell.execute_reply.started":"2024-12-29T19:19:33.405010Z","shell.execute_reply":"2024-12-29T19:19:33.727264Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df = pd.concat([train,coord],axis=1)","metadata":{"execution":{"iopub.status.busy":"2024-12-29T19:19:33.728962Z","iopub.execute_input":"2024-12-29T19:19:33.729236Z","iopub.status.idle":"2024-12-29T19:19:33.747764Z","shell.execute_reply.started":"2024-12-29T19:19:33.729214Z","shell.execute_reply":"2024-12-29T19:19:33.746834Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df['x1']=pd.to_numeric(df['x1'])\ndf['y1']=pd.to_numeric(df['y1'])\ndf['w']=pd.to_numeric(df['w'])\ndf['h']=pd.to_numeric(df['h'])\n","metadata":{"execution":{"iopub.status.busy":"2024-12-29T19:19:33.748937Z","iopub.execute_input":"2024-12-29T19:19:33.749279Z","iopub.status.idle":"2024-12-29T19:19:33.945142Z","shell.execute_reply.started":"2024-12-29T19:19:33.749249Z","shell.execute_reply":"2024-12-29T19:19:33.944175Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df['x2']=df['x1']+df['w']\ndf['y2']=df['y1']+df['h']","metadata":{"execution":{"iopub.status.busy":"2024-12-29T19:19:33.946256Z","iopub.execute_input":"2024-12-29T19:19:33.946592Z","iopub.status.idle":"2024-12-29T19:19:33.954400Z","shell.execute_reply.started":"2024-12-29T19:19:33.946563Z","shell.execute_reply":"2024-12-29T19:19:33.953469Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df","metadata":{"execution":{"iopub.status.busy":"2024-12-29T19:19:33.955551Z","iopub.execute_input":"2024-12-29T19:19:33.955868Z","iopub.status.idle":"2024-12-29T19:19:33.974695Z","shell.execute_reply.started":"2024-12-29T19:19:33.955840Z","shell.execute_reply":"2024-12-29T19:19:33.973818Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Drop unneeded column:","metadata":{}},{"cell_type":"code","source":"df.drop(['bbox','width','height','w','h','source'],axis=1,inplace=True)","metadata":{"execution":{"iopub.status.busy":"2024-12-29T19:19:33.975910Z","iopub.execute_input":"2024-12-29T19:19:33.976723Z","iopub.status.idle":"2024-12-29T19:19:33.993469Z","shell.execute_reply.started":"2024-12-29T19:19:33.976700Z","shell.execute_reply":"2024-12-29T19:19:33.992687Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.head()","metadata":{"execution":{"iopub.status.busy":"2024-12-29T19:19:33.998072Z","iopub.execute_input":"2024-12-29T19:19:33.998358Z","iopub.status.idle":"2024-12-29T19:19:34.008765Z","shell.execute_reply.started":"2024-12-29T19:19:33.998336Z","shell.execute_reply":"2024-12-29T19:19:34.007950Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Take the unique ids of the images:","metadata":{}},{"cell_type":"code","source":"unique_imgs=df.image_id.unique()\nunique_imgs","metadata":{"execution":{"iopub.status.busy":"2024-12-29T19:19:34.009857Z","iopub.execute_input":"2024-12-29T19:19:34.010182Z","iopub.status.idle":"2024-12-29T19:19:34.030408Z","shell.execute_reply.started":"2024-12-29T19:19:34.010153Z","shell.execute_reply":"2024-12-29T19:19:34.029652Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Make custom class for preparing the data:","metadata":{}},{"cell_type":"code","source":"class custDat(torch.utils.data.Dataset):\n    def __init__(self, df, unique_imgs, indices):\n        self.df = df\n        self.unique_imgs = unique_imgs\n        self.indices = indices\n    \n    def __len__(self):\n        return len(self.indices)\n    \n    def __getitem__(self, idx):\n        image_name = self.unique_imgs[self.indices[idx]]\n        boxes = self.df[self.df.image_id == image_name].values[:, 1:].astype(\"float\")\n        img = Image.open(\"../input/global-wheat-detection/train/\" + image_name + \".jpg\").convert('RGB')\n        labels = torch.ones(boxes.shape[0], dtype=torch.int64)\n        target = {}\n        target[\"boxes\"] = torch.tensor(boxes)\n        target[\"label\"] = labels\n        return T.ToTensor()(img), target\n","metadata":{"execution":{"iopub.status.busy":"2024-12-29T19:19:34.031415Z","iopub.execute_input":"2024-12-29T19:19:34.031661Z","iopub.status.idle":"2024-12-29T19:19:34.040110Z","shell.execute_reply.started":"2024-12-29T19:19:34.031642Z","shell.execute_reply":"2024-12-29T19:19:34.039250Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# spit the data int train and validation:","metadata":{}},{"cell_type":"code","source":"train_inds , val_inds =train_test_split(range(unique_imgs.shape[0]),test_size=0.1)","metadata":{"execution":{"iopub.status.busy":"2024-12-29T19:19:34.041152Z","iopub.execute_input":"2024-12-29T19:19:34.041420Z","iopub.status.idle":"2024-12-29T19:19:34.050796Z","shell.execute_reply.started":"2024-12-29T19:19:34.041395Z","shell.execute_reply":"2024-12-29T19:19:34.049927Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def custom_collate(data):\n    return data","metadata":{"execution":{"iopub.status.busy":"2024-12-29T19:19:34.051838Z","iopub.execute_input":"2024-12-29T19:19:34.052146Z","iopub.status.idle":"2024-12-29T19:19:34.061603Z","shell.execute_reply.started":"2024-12-29T19:19:34.052126Z","shell.execute_reply":"2024-12-29T19:19:34.060822Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Call the data loader to prepare it to the model:","metadata":{}},{"cell_type":"code","source":"train_dl = torch.utils.data.DataLoader(custDat(df,unique_imgs,train_inds),batch_size=16,shuffle=True,collate_fn=custom_collate,pin_memory=True if torch.cuda.is_available() else False)\nval_dl = torch.utils.data.DataLoader(custDat(df,unique_imgs,val_inds),batch_size=8,shuffle=True,collate_fn=custom_collate,pin_memory=True if torch.cuda.is_available() else False)\n","metadata":{"execution":{"iopub.status.busy":"2024-12-29T19:59:26.256562Z","iopub.execute_input":"2024-12-29T19:59:26.257321Z","iopub.status.idle":"2024-12-29T19:59:26.261959Z","shell.execute_reply.started":"2024-12-29T19:59:26.257292Z","shell.execute_reply":"2024-12-29T19:59:26.261094Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Modeling:","metadata":{}},{"cell_type":"code","source":"model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)\nnum_classes=2\nin_features=model.roi_heads.box_predictor.cls_score.in_features\nmodel.roi_heads.box_predictor =  FastRCNNPredictor(in_features,num_classes)","metadata":{"execution":{"iopub.status.busy":"2024-12-29T19:19:34.096819Z","iopub.execute_input":"2024-12-29T19:19:34.097133Z","iopub.status.idle":"2024-12-29T19:19:34.871389Z","shell.execute_reply.started":"2024-12-29T19:19:34.097106Z","shell.execute_reply":"2024-12-29T19:19:34.870568Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')","metadata":{"execution":{"iopub.status.busy":"2024-12-29T19:19:34.872558Z","iopub.execute_input":"2024-12-29T19:19:34.872884Z","iopub.status.idle":"2024-12-29T19:19:34.876987Z","shell.execute_reply.started":"2024-12-29T19:19:34.872851Z","shell.execute_reply":"2024-12-29T19:19:34.876174Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"device","metadata":{"execution":{"iopub.status.busy":"2024-12-29T19:19:34.878021Z","iopub.execute_input":"2024-12-29T19:19:34.878399Z","iopub.status.idle":"2024-12-29T19:19:34.895360Z","shell.execute_reply.started":"2024-12-29T19:19:34.878368Z","shell.execute_reply":"2024-12-29T19:19:34.894498Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"optimizer = torch.optim.SGD(model.parameters(),lr=0.001,momentum=0.9,weight_decay=0.005)\nnum_epochs=5","metadata":{"execution":{"iopub.status.busy":"2024-12-29T19:19:34.896519Z","iopub.execute_input":"2024-12-29T19:19:34.896820Z","iopub.status.idle":"2024-12-29T19:19:34.905281Z","shell.execute_reply.started":"2024-12-29T19:19:34.896793Z","shell.execute_reply":"2024-12-29T19:19:34.904448Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Train the model with 5 epochs and prin the loss:","metadata":{}},{"cell_type":"code","source":"model.to(device)\nfor epochs in range (num_epochs):\n    epoch_loss = 0\n    for data in train_dl:\n        imgs=[]\n        targets = []\n        for d in data :\n            imgs.append(d[0].to(device))\n            targ = {}\n            targ['boxes']=d[1]['boxes'].to(device)\n            targ['labels']=d[1]['label'].to(device)\n            targets.append(targ)\n        loss_dict = model(imgs,targets)\n        loss= sum(v for v in loss_dict.values())\n        epoch_loss += loss.cpu().detach().numpy()\n        optimizer.zero_grad()\n        loss.backward()\n        optimizer.step()\n    print(epoch_loss) \n            \n            ","metadata":{"execution":{"iopub.status.busy":"2024-12-29T19:19:34.906260Z","iopub.execute_input":"2024-12-29T19:19:34.906498Z","iopub.status.idle":"2024-12-29T19:43:41.205208Z","shell.execute_reply.started":"2024-12-29T19:19:34.906478Z","shell.execute_reply":"2024-12-29T19:43:41.204266Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Evaluate the model","metadata":{}},{"cell_type":"code","source":"model.eval()\ndata = iter(val_dl).__next__()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-29T19:43:41.206456Z","iopub.execute_input":"2024-12-29T19:43:41.206720Z","iopub.status.idle":"2024-12-29T19:43:41.412189Z","shell.execute_reply.started":"2024-12-29T19:43:41.206697Z","shell.execute_reply":"2024-12-29T19:43:41.411248Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"img= data[0][0]\nboxes=data[0][1]['boxes']\nlabels=data[0][1]['label']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-29T19:43:41.413376Z","iopub.execute_input":"2024-12-29T19:43:41.413644Z","iopub.status.idle":"2024-12-29T19:43:41.417799Z","shell.execute_reply.started":"2024-12-29T19:43:41.413622Z","shell.execute_reply":"2024-12-29T19:43:41.416933Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"output = model([img.to(device)])\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-29T19:43:41.418809Z","iopub.execute_input":"2024-12-29T19:43:41.419065Z","iopub.status.idle":"2024-12-29T19:43:41.868186Z","shell.execute_reply.started":"2024-12-29T19:43:41.419022Z","shell.execute_reply":"2024-12-29T19:43:41.867280Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### output os the evaluation:","metadata":{}},{"cell_type":"code","source":"output","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-29T19:43:41.869319Z","iopub.execute_input":"2024-12-29T19:43:41.869583Z","iopub.status.idle":"2024-12-29T19:43:41.911608Z","shell.execute_reply.started":"2024-12-29T19:43:41.869562Z","shell.execute_reply":"2024-12-29T19:43:41.910777Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"out_bbox=output[0]['boxes']\nout_scores=output[0]['scores']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-29T19:43:41.912436Z","iopub.execute_input":"2024-12-29T19:43:41.912673Z","iopub.status.idle":"2024-12-29T19:43:41.917153Z","shell.execute_reply.started":"2024-12-29T19:43:41.912653Z","shell.execute_reply":"2024-12-29T19:43:41.916117Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"keep = torchvision.ops.nms(out_bbox,out_scores,0.45)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-29T19:43:41.918403Z","iopub.execute_input":"2024-12-29T19:43:41.918686Z","iopub.status.idle":"2024-12-29T19:43:41.930645Z","shell.execute_reply.started":"2024-12-29T19:43:41.918658Z","shell.execute_reply":"2024-12-29T19:43:41.928972Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"out_bbox.shape , keep.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-29T19:43:41.931813Z","iopub.execute_input":"2024-12-29T19:43:41.932144Z","iopub.status.idle":"2024-12-29T19:43:41.946397Z","shell.execute_reply.started":"2024-12-29T19:43:41.932115Z","shell.execute_reply":"2024-12-29T19:43:41.945637Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### prediction detection:","metadata":{}},{"cell_type":"code","source":"im = (img.permute(1,2,0).cpu().detach().numpy()*255).astype('uint8')\nim","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-29T19:43:41.949911Z","iopub.execute_input":"2024-12-29T19:43:41.950159Z","iopub.status.idle":"2024-12-29T19:43:41.963114Z","shell.execute_reply.started":"2024-12-29T19:43:41.950140Z","shell.execute_reply":"2024-12-29T19:43:41.962359Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"vsample = Image.fromarray(im)\ndraw = ImageDraw.Draw(vsample)\nfor box in boxes :\n    draw.rectangle(list(box),fill=None,outline='red')\nvsample","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-29T19:43:41.964319Z","iopub.execute_input":"2024-12-29T19:43:41.964546Z","iopub.status.idle":"2024-12-29T19:43:42.408264Z","shell.execute_reply.started":"2024-12-29T19:43:41.964528Z","shell.execute_reply":"2024-12-29T19:43:42.407062Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Save the model state\ntorch.save(model.state_dict(), 'fasterrcnn_resnet50_fpn_kelompok2.pth')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-29T19:43:42.409516Z","iopub.execute_input":"2024-12-29T19:43:42.409836Z","iopub.status.idle":"2024-12-29T19:43:42.640483Z","shell.execute_reply.started":"2024-12-29T19:43:42.409810Z","shell.execute_reply":"2024-12-29T19:43:42.639792Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from IPython.display import FileLink\n\noutput_file_path = '/kaggle/working/fasterrcnn_resnet50_fpn_kelompok2.pth'  # Path to your output file\nFileLink(output_file_path)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-29T19:43:42.641519Z","iopub.execute_input":"2024-12-29T19:43:42.641836Z","iopub.status.idle":"2024-12-29T19:43:42.647654Z","shell.execute_reply.started":"2024-12-29T19:43:42.641805Z","shell.execute_reply":"2024-12-29T19:43:42.646709Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nfrom torchvision.models.detection import fasterrcnn_resnet50_fpn\n\n# Initialize the model\nmodel = fasterrcnn_resnet50_fpn(pretrained=False, num_classes=num_classes)  # Replace 'num_classes' with your dataset's number of classes\n\n# Load the trained weights\nmodel.load_state_dict(torch.load('fasterrcnn_resnet50_fpn_kelompok2.pth'))\n\n# Set the model to evaluation mode\nmodel.eval()\n\n# Move the model to the appropriate device\ndevice = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\nmodel = model.to(device)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-29T20:03:56.276768Z","iopub.execute_input":"2024-12-29T20:03:56.277604Z","iopub.status.idle":"2024-12-29T20:03:57.758940Z","shell.execute_reply.started":"2024-12-29T20:03:56.277574Z","shell.execute_reply":"2024-12-29T20:03:57.758248Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from PIL import Image\nfrom torchvision import transforms\n\n# Load the test image\nimage_path = \"/kaggle/input/global-wheat-detection/test/2fd875eaa.jpg\"  # Replace with the path to your test image\nimage = Image.open(image_path).convert(\"RGB\")\n\n# Define the transformation\ntransform = transforms.Compose([\n    transforms.ToTensor(),  # Converts to PyTorch tensor and scales pixel values to [0, 1]\n    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])  # Normalization\n])\n\n# Apply the transformation\nimg_tensor = transform(image).to(device)  # Move to device\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-29T20:04:33.667715Z","iopub.execute_input":"2024-12-29T20:04:33.668079Z","iopub.status.idle":"2024-12-29T20:04:33.704607Z","shell.execute_reply.started":"2024-12-29T20:04:33.668026Z","shell.execute_reply":"2024-12-29T20:04:33.703667Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Add a batch dimension to the image tensor\nimg_tensor = img_tensor.unsqueeze(0)\n\n# Make predictions\nwith torch.no_grad():\n    predictions = model(img_tensor)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-29T20:04:47.903867Z","iopub.execute_input":"2024-12-29T20:04:47.904221Z","iopub.status.idle":"2024-12-29T20:04:47.965972Z","shell.execute_reply.started":"2024-12-29T20:04:47.904193Z","shell.execute_reply":"2024-12-29T20:04:47.965349Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"pred_boxes = predictions[0]['boxes'].cpu()\npred_labels = predictions[0]['labels'].cpu()\npred_scores = predictions[0]['scores'].cpu()\n\n# Filter predictions by confidence score\nthreshold = 0\nfiltered_indices = pred_scores > threshold\nfiltered_boxes = pred_boxes[filtered_indices]\nfiltered_labels = pred_labels[filtered_indices]\nfiltered_scores = pred_scores[filtered_indices]\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-29T20:07:44.805846Z","iopub.execute_input":"2024-12-29T20:07:44.806297Z","iopub.status.idle":"2024-12-29T20:07:44.812031Z","shell.execute_reply.started":"2024-12-29T20:07:44.806264Z","shell.execute_reply":"2024-12-29T20:07:44.811266Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from torchvision.utils import draw_bounding_boxes\nimport matplotlib.pyplot as plt\nimport torchvision.transforms.functional as F\n\n# Assuming filtered_boxes, filtered_labels, and filtered_scores are already defined\n# Use a simple mapping for wheat\nclass_mapping = {1: \"Wheat\"}\n\n# Convert labels to strings for visualization\nfiltered_labels_str = [class_mapping.get(label.item(), \"Unknown\") for label in filtered_labels]\n\n# Denormalize the image for visualization\ndenorm_transform = transforms.Normalize(\n    mean=[-0.485 / 0.229, -0.456 / 0.224, -0.406 / 0.225],\n    std=[1 / 0.229, 1 / 0.224, 1 / 0.225]\n)\nimg_tensor_denorm = denorm_transform(img_tensor[0].cpu())\n\n# Convert the image to uint8 for drawing\nimg_tensor_uint8 = (img_tensor_denorm * 255).clamp(0, 255).byte()\n\n# Draw bounding boxes on the image\nimg_with_boxes = draw_bounding_boxes(\n    img_tensor_uint8, \n    boxes=filtered_boxes, \n    labels=filtered_labels_str, \n    colors=\"green\",  # Set the box color (e.g., green)\n    width=2          # Set the line width\n)\n\n# Convert to PIL image and display\nimg_with_boxes_pil = F.to_pil_image(img_with_boxes)\nplt.figure(figsize=(12, 8))\nplt.imshow(img_with_boxes_pil)\nplt.axis('off')\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-29T20:07:48.486319Z","iopub.execute_input":"2024-12-29T20:07:48.487097Z","iopub.status.idle":"2024-12-29T20:07:48.975773Z","shell.execute_reply.started":"2024-12-29T20:07:48.487066Z","shell.execute_reply":"2024-12-29T20:07:48.974638Z"}},"outputs":[],"execution_count":null}]}