Views
No views yet
facebook/maskformer-swin-tiny-coco pre-trained checkpoint as its backbone, with a Swin-Tiny transformer architecture. The model predicts a set of masks and corresponding labels for three classes: "background," "normal," and "abnormal," with an additional "no object" class handled internally by MaskFormer. The model was trained on a small custom dataset as a proof-of-concept for automating germination counting in agricultural research.
1import requests
2import torch
3from PIL import Image
4from transformers import AutoImageProcessor, MaskFormerForInstanceSegmentation
5
6# Load GermiNet fine-tuned on custom germination dataset
7processor = AutoImageProcessor.from_pretrained("your-username/germi-net")
8model = MaskFormerForInstanceSegmentation.from_pretrained("your-username/germi-net")
9
10# Load an image (replace with your image URL or local path)
11url = "https://example.com/path/to/germination-image.jpg"
12image = Image.open(requests.get(url, stream=True).raw)
13# Alternatively, use a local image
14# image = Image.open("path/to/your/image.jpg")
15inputs = processor(images=image, return_tensors="pt")
16
17# Run inference
18with torch.no_grad():
19 outputs = model(**inputs)
20
21# Model predicts class_queries_logits and masks_queries_logits
22class_queries_logits = outputs.class_queries_logits # Shape: (batch_size, num_queries, num_classes + 1)
23masks_queries_logits = outputs.masks_queries_logits # Shape: (batch_size, num_queries, height, width)
24
25# Post-process predictions
26predicted_classes = class_queries_logits.argmax(-1).cpu().numpy()
27mask_predictions = masks_queries_logits.sigmoid().cpu().numpy()
28binary_masks = (mask_predictions > 0.5).astype(np.uint8)
29
30# Map predictions to labels
31id2label = {0: "background", 1: "normal", 2: "abnormal", 3: "no object"}
32predicted_labels = [id2label[cls] for cls in predicted_classes[0]]
33print("Predicted labels:", predicted_labels)
34
35# Optional: Visualize (requires matplotlib and cv2)
36import numpy as np
37import matplotlib.pyplot as plt
38import cv2
39
40visualization_size = (800, 800)
41resized_masks = np.zeros((binary_masks.shape[1], *visualization_size), dtype=np.uint8)
42for i in range(binary_masks.shape[1]):
43 resized_masks[i] = cv2.resize(binary_masks[0, i], visualization_size, interpolation=cv2.INTER_NEAREST)
44
45image_np = np.array(image)
46aspect_ratio = image_np.shape[1] / image_np.shape[0]
47new_height = visualization_size[0]
48new_width = int(new_height * aspect_ratio)
49resized_image = cv2.resize(image_np, (new_width, new_height), interpolation=cv2.INTER_LINEAR)
50if new_width != visualization_size[1]:
51 start_x = (new_width - visualization_size[1]) // 2
52 resized_image = resized_image[:, start_x:start_x + visualization_size[1]]