Spaces:
Sleeping
Sleeping
Update app.py
Browse files1 unmodified line23456789101112131415161718192021225 unmodified lines2829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798993 unmodified lines1031041051061 unmodified lineimport torchimport numpy as npimport iofrom PIL import Imageimport matplotlib.pyplot as pltimport matplotlib.patches as patchesimport warningsimport gradio as grfrom torchvision.models.detection.faster_rcnn import FastRCNNPredictorimport torchvision# Disable Tkinter-related warningswarnings.filterwarnings("ignore", category=RuntimeWarning)# Use a non-interactive Matplotlib backendimport matplotlibmatplotlib.use('Agg')# Path to the local model fileLOCAL_MODEL_PATH = "faster_rcnn_state.pth"5 unmodified linesnum_classes = 21 # 20 classes + backgroundin_features = model.roi_heads.box_predictor.cls_score.in_featuresmodel.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)# Load weightsmodel.load_state_dict(torch.load(LOCAL_MODEL_PATH, map_location='cpu'))model.eval()device = torch.device("cuda" if torch.cuda.is_available() else "cpu")model = model.to(device)else:print("Failed to load model")# Dictionary for class labels (adjust based on your model's classes)classes = {0: 'background', 1: 'aeroplane', 2: 'bicycle', 3: 'bird', 4: 'boat', 5: 'bottle', 6: 'bus', 7: 'car', 8: 'cat', 9: 'chair', 10: 'cow',11: 'diningtable', 12: 'dog', 13: 'horse', 14: 'motorbike', 15: 'person', 16: 'pottedplant', 17: 'sheep', 18: 'sofa', 19: 'train', 20: 'tvmonitor'}def obj_detector(image_file):img = np.array(Image.open(io.BytesIO(image_file)).convert("RGB"))img = img.astype(np.float32)img /= 255.0img = torch.from_numpy(img)img = img.unsqueeze(0)img = img.permute(0, 3, 1, 2)model.eval()detection_threshold = 0.70img = list(im.to(device) for im in img)output = model(img)boxes = output[0]['boxes'].data.cpu().numpy()scores = output[0]['scores'].data.cpu().numpy()labels = output[0]['labels'].data.cpu().numpy()labels = labels[scores >= detection_threshold]boxes = boxes[scores >= detection_threshold].astype(np.int32)scores = scores[scores >= detection_threshold]boxes[:, 2] = boxes[:, 2] - boxes[:, 0]boxes[:, 3] = boxes[:, 3] - boxes[:, 1]fig, ax = plt.subplots(figsize=(12, 8))ax.imshow(img[0].permute(1, 2, 0).cpu().numpy())for i, box in enumerate(boxes):x1, y1, w, h = boxx2 = x1 + wy2 = y1 + hrect = patches.Rectangle((x1, y1), w, h, linewidth=2, edgecolor='r', facecolor='none')ax.add_patch(rect)ax.text(x1, y1, classes[labels[i]], color='white', backgroundcolor='red', fontsize=10)buffered = io.BytesIO()fig.savefig(buffered, format="JPEG")plt.close()labeled_image = Image.open(buffered).convert("RGB")return labeled_imagedef inference(image):image = image.convert("RGB")image_file = io.BytesIO()image.save(image_file, format="JPEG")image_file = image_file.getvalue()labeled_image = obj_detector(image_file)return labeled_imageiface = gr.Interface(fn=inference,3 unmodified linesdescription="Upload an image to detect objects using Faster R-CNN.",)iface.launch(share=True)1 unmodified line234567891011125 unmodified lines18192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384853 unmodified lines899091921 unmodified lineimport torchimport numpy as npimport iofrom PIL import Image, ImageDraw, ImageFontimport gradio as grfrom torchvision.models.detection.faster_rcnn import FastRCNNPredictorimport torchvision# Path to the local model fileLOCAL_MODEL_PATH = "faster_rcnn_state.pth"5 unmodified linesnum_classes = 21 # 20 classes + backgroundin_features = model.roi_heads.box_predictor.cls_score.in_featuresmodel.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)# Load weightsmodel.load_state_dict(torch.load(LOCAL_MODEL_PATH, map_location='cpu'))model.eval()device = torch.device("cuda" if torch.cuda.is_available() else "cpu")model = model.to(device)else:print("Failed to load model")# Dictionary for class labelsclasses = {0: 'background', 1: 'aeroplane', 2: 'bicycle', 3: 'bird', 4: 'boat', 5: 'bottle', 6: 'bus', 7: 'car', 8: 'cat', 9: 'chair', 10: 'cow', 11: 'diningtable', 12: 'dog', 13: 'horse', 14: 'motorbike', 15: 'person', 16: 'pottedplant', 17: 'sheep', 18: 'sofa', 19: 'train', 20: 'tvmonitor'}def obj_detector(image):# Convert image to RGBimg = image.convert("RGB")# Convert to numpy array and normalizeimg_array = np.array(img).astype(np.float32) / 255.0# Convert to torch tensorimg_tensor = torch.from_numpy(img_array).permute(2, 0, 1).unsqueeze(0)# Move tensor to the same device as the modelimg_tensor = img_tensor.to(device)with torch.no_grad():prediction = model(img_tensor)detection_threshold = 0.7boxes = prediction[0]['boxes'].cpu().numpy()labels = prediction[0]['labels'].cpu().numpy()scores = prediction[0]['scores'].cpu().numpy()# Filter detections based on detection thresholdmask = scores >= detection_thresholdboxes = boxes[mask]labels = labels[mask]scores = scores[mask]# Create a new image for drawingdraw = ImageDraw.Draw(img)# Load a fonttry:font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 20)except IOError:font = ImageFont.load_default()# Draw bounding boxes and labels on the imagefor box, label, score in zip(boxes, labels, scores):box = box.astype(int)x1, y1, x2, y2 = boxdraw.rectangle(((x1, y1), (x2, y2)), outline="red", width=3)label_text = f"{classes[label]}: {score:.2f}"draw.text((x1, y1-25), label_text, fill="red", font=font)return imgdef inference(image):try:labeled_image = obj_detector(image)return labeled_imageexcept Exception as e:print(f"An error occurred during inference: {str(e)}")raise gr.Error(f"Inference failed: {str(e)}")iface = gr.Interface(fn=inference,3 unmodified linesdescription="Upload an image to detect objects using Faster R-CNN.",)iface.launch(share=True, show_error=True)
app.py+46-60