data354/Palm_counting
0
1import streamlit as st2import torch3import torchvision4import cv25import numpy as np6import torch.nn as nn7from torchvision.ops import box_iou8from PIL import Image9import albumentations as A10from albumentations.pytorch import ToTensorV211 12# apply nms algorithm13def apply_nms(orig_prediction, iou_thresh=0.3):14 # torchvision returns the indices of the bboxes to keep15 keep = torchvision.ops.nms(orig_prediction['boxes'], orig_prediction['scores'], iou_thresh)16 final_prediction = orig_prediction17 final_prediction['boxes'] = final_prediction['boxes'][keep]18 final_prediction['scores'] = final_prediction['scores'][keep]19 final_prediction['labels'] = final_prediction['labels'][keep]20 21 return final_prediction22 23# Draw the bounding box24def plot_img_bbox(img, target):25 h,w,c = img.shape26 for box in (target['boxes']):27 xmin, ymin, xmax, ymax = int((box[0].cpu()/1024)*w), int((box[1].cpu()/1024)*h), int((box[2].cpu()/1024)*w),int((box[3].cpu()/1024)*h)28 cv2.rectangle(img, (xmin, ymin), (xmax, ymax), (0, 0, 255), 2)29 label = "palm"30 # Add the label and confidence score31 label = f'{label}'32 cv2.putText(img, label, (xmin, ymin - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)33 34 # Display the image with detections35 filename = 'pred.jpg'36 cv2.imwrite(filename, img)37 38# transform image39test_transforms = A.Compose([40 A.Resize(height=1024, width=1024, always_apply=True),41 A.Normalize(always_apply=True),42 ToTensorV2(always_apply=True),])43 44# select device (whether GPU or CPU)45device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')46 47# model loading48model = torch.load('pickel.pth',map_location=torch.device('cpu'))49model = model.to(device)50 51st.title("🌴Palm trees detection🌴")52 53file_name = st.file_uploader("Upload oil palm tree image")54 55if file_name is not None:56 col1, col2 = st.columns(2)57 58 image = np.array(Image.open(file_name))59 col1.image(image, use_column_width=True)60 transformed = test_transforms(image= image)61 image_transformed = transformed["image"]62 image_transformed = image_transformed.unsqueeze(0)63 image_transformed = image_transformed.to(device)64 # inference65 model.eval()66 with torch.no_grad():67 predictions = model(image_transformed)[0]68 69 nms_prediction = apply_nms(predictions, iou_thresh=0.1)70 71 plot_img_bbox(image, nms_prediction)72 pred = np.array(Image.open("pred.jpg"))73 col2.image(pred, use_column_width=True)74 word = "Number of palm trees detected : "+str(len(nms_prediction["boxes"]))75 st.write(word)76 77 78 79 80 81 82 83 84 85 