import torch import cv2 import os import torch.nn as nn import numpy as np import torchvision from torchvision.ops import box_iou from PIL import Image import albumentations as A from albumentations.pytorch import ToTensorV2 import cv2 import tqdm import gc from time import sleep import shutil from timeit import default_timer as timer from typing import Tuple, Dict import warnings warnings.filterwarnings('ignore') # apply nms algorithm def apply_nms(orig_prediction, iou_thresh=0.3): # torchvision returns the indices of the bboxes to keep keep = torchvision.ops.nms(orig_prediction['boxes'], orig_prediction['scores'], iou_thresh) final_prediction = orig_prediction final_prediction['boxes'] = final_prediction['boxes'][keep] final_prediction['scores'] = final_prediction['scores'][keep] final_prediction['labels'] = final_prediction['labels'][keep] return final_prediction def apply_nms2(orig_prediction, iou_thresh=0.3): # torchvision returns the indices of the bboxes to keep preds = [] for prediction in orig_prediction: keep = torchvision.ops.nms(prediction['boxes'], prediction['scores'], iou_thresh) final_prediction = prediction final_prediction['boxes'] = final_prediction['boxes'][keep] final_prediction['scores'] = final_prediction['scores'][keep] final_prediction['labels'] = final_prediction['labels'][keep] preds.append(final_prediction) return preds # Draw the bounding box def plot_img_bbox(img, target): h,w,c = img.shape for box in (target['boxes']): 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) cv2.rectangle(img, (xmin, ymin), (xmax, ymax), (0, 0, 255), 2) label = "palm" # Add the label and confidence score label = f'{label}' cv2.putText(img, label, (xmin, ymin - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2) # Display the image with detections #filename = 'pred.jpg' #cv2.imwrite(filename, img) return img def crop(image,size=1024): #input = os.path.join(path,image) #img = cv2.imread(input) img = image.copy() H, W,_ = img.shape h = (H//size) w = (W//size) H1 = h*size W1 = w*size os.makedirs("images", exist_ok=True) images = [] #images_truth = [] locations = [] if H1 < H : chevauche_h = H-H1 rest_h = 1024-chevauche_h val_h = H1-rest_h H2 = [x for x in range(0,H1,size)] +[val_h] else : H2 = [x for x in range(0,H1,size)] if W1