Upload 7 files
Browse filesFiles changed (7)
- app.pyAdded+283
- keypointrcnn_3d_chair.onnxAdded+3
- requirements.txtAdded+7
- sample1.jpgAdded
- sample2.jpgAdded
- sample3.jpgAdded
- sample4.jpgAdded
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283# app.pyimport gradio as grfrom PIL import Imageimport spacesimport onnxruntimeimport numpy as npimport cv2
class_names = ['bg', 'Grasper', 'Harmonic_Ace', 'Myoma_Screw', 'Needle_Holder', 'Suction', 'Trocar']
colors = [ (0, 0, 0), (0, 0, 255), # Red - Grasper (0, 255, 0), # Green - Harmonic_Ace (255, 0, 0), # Blue - Myoma_Screw (0, 255, 255), # Yellow - Needle_Holder (255, 0, 255), # Magenta - Suction (255, 255, 0) # Cyan - Trocar]
def sigmoid(x): return 1 / (1 + np.exp(-x))
def draw_detections(image, boxes, scores, class_ids, mask_alpha=0.3, mask_maps=None): img_height, img_width = image.shape[:2] size = min([img_height, img_width]) * 0.0015 text_thickness = int(min([img_height, img_width]) * 0.003)
mask_img = draw_masks(image, boxes, class_ids, mask_alpha, mask_maps)
# Draw bounding boxes and labels of detections for box, score, class_id in zip(boxes, scores, class_ids): color = colors[class_id]
x1, y1, x2, y2 = box.astype(int)
# Draw rectangle cv2.rectangle(mask_img, (x1, y1), (x2, y2), color, 2)
label = class_names[class_id] caption = f'{label} {int(score * 100)}%' (tw, th), _ = cv2.getTextSize(text=caption, fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=size, thickness=text_thickness) th = int(th * 1.2)
# cv2.rectangle(mask_img, (x1, y1), # (x1 + tw, y1 - th), color, -1)
cv2.putText(mask_img, caption, (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, size, color, text_thickness, cv2.LINE_AA)
return mask_img
def draw_masks(image, boxes, class_ids, mask_alpha=0.3, mask_maps=None): mask_img = image.copy()
# Draw bounding boxes and labels of detections for i in range(len(mask_maps)): box = boxes[i] class_id = class_ids[i]
color = colors[class_id]
x1, y1, x2, y2 = box.astype(int)
# Draw fill mask image if mask_maps is None: cv2.rectangle(mask_img, (x1, y1), (x2, y2), color, -1) else: crop_mask = mask_maps[i][y1:y2, x1:x2, np.newaxis] crop_mask_img = mask_img[y1:y2, x1:x2] crop_mask_img = crop_mask_img * (1 - crop_mask) + crop_mask * color mask_img[y1:y2, x1:x2] = crop_mask_img
return cv2.addWeighted(mask_img, mask_alpha, image, 1 - mask_alpha, 0)
class YOLOSeg: def __init__(self, path, conf_thres=0.7, num_masks=32): self.conf_threshold = conf_thres self.num_masks = num_masks
# Initialize model self.initialize_model(path)
def __call__(self, image): return self.segment_objects(image)
def initialize_model(self, path): self.session2 = onnxruntime.InferenceSession(path, providers=['CUDAExecutionProvider', 'CPUExecutionProvider']) # Get model info self.get_input_details() self.get_output_details()
def segment_objects(self, image): input_tensor = self.prepare_input(image)
# Perform inference on the image outputs = self.inference(input_tensor)
self.boxes, self.scores, self.class_ids, mask_pred = self.process_box_output(outputs[0]) self.mask_maps = self.process_mask_output(mask_pred, outputs[1])
return self.boxes, self.scores, self.class_ids, self.mask_maps
def prepare_input(self, image): self.img_height, self.img_width = image.shape[:2]
input_img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Resize input image input_img = cv2.resize(input_img, (self.input_width, self.input_height))
# Scale input pixel values to 0 to 1 input_img = input_img / 255.0 input_img = input_img.transpose(2, 0, 1) input_tensor = input_img[np.newaxis, :, :, :].astype(np.float32)
return input_tensor
def inference(self, input_tensor): outputs = self.session2.run(self.output_names, {self.input_names[0]: input_tensor}) return outputs
def process_box_output(self, box_output): preds = np.squeeze(box_output) # (300, 38)
boxes = preds[:, 0:4] # xyxy already scores = preds[:, 4] # confidence class_ids = preds[:, 5].astype(int) mask_preds = preds[:, 6:] # 32 mask coeffs
keep = scores > self.conf_threshold if not np.any(keep): return [], [], [], np.array([])
boxes = boxes[keep] scores = scores[keep] class_ids = class_ids[keep] mask_preds = mask_preds[keep]
# Rescale boxes from input size to original image size boxes[:, [0, 2]] *= self.img_width / self.input_width boxes[:, [1, 3]] *= self.img_height / self.input_height
return boxes, scores, class_ids, mask_preds
def process_mask_output(self, mask_coeffs, proto):
if mask_coeffs.shape[0] == 0: return []
proto = np.squeeze(proto) # (32, mh, mw) mh, mw = proto.shape[1:]
# (N, mh, mw) masks = sigmoid(mask_coeffs @ proto.reshape(32, -1)) masks = masks.reshape(-1, mh, mw)
valid_masks = []
for i, box in enumerate(self.boxes): x1, y1, x2, y2 = box.astype(int)
if x2 <= x1 or y2 <= y1: continue
# map box to proto space px1 = int(x1 / self.img_width * mw) px2 = int(x2 / self.img_width * mw) py1 = int(y1 / self.img_height * mh) py2 = int(y2 / self.img_height * mh)
px1 = np.clip(px1, 0, mw) px2 = np.clip(px2, 0, mw) py1 = np.clip(py1, 0, mh) py2 = np.clip(py2, 0, mh)
if px2 <= px1 or py2 <= py1: continue
crop = masks[i, py1:py2, px1:px2] crop = cv2.resize(crop, (x2 - x1, y2 - y1)) crop = (crop > 0.5).astype(np.uint8)
full = np.zeros((self.img_height, self.img_width), dtype=np.uint8) full[y1:y2, x1:x2] = crop
valid_masks.append(full)
return np.array(valid_masks)
def draw_detections(self, image, draw_scores=True, mask_alpha=0.4): return draw_detections(image, self.boxes, self.scores, self.class_ids, mask_alpha)
def draw_masks(self, image, draw_scores=True, mask_alpha=0.7): return draw_detections(image, self.boxes, self.scores, self.class_ids, mask_alpha, mask_maps=self.mask_maps)
def get_input_details(self): model_inputs = self.session2.get_inputs() self.input_names = [model_inputs[i].name for i in range(len(model_inputs))]
self.input_shape = model_inputs[0].shape self.input_height = self.input_shape[2] self.input_width = self.input_shape[3]
def get_output_details(self): model_outputs = self.session2.get_outputs() self.output_names = [model_outputs[i].name for i in range(len(model_outputs))]
@staticmethod def rescale_boxes(boxes, input_shape, image_shape): # Rescale boxes to original image dimensions input_shape = np.array([input_shape[1], input_shape[0], input_shape[1], input_shape[0]]) boxes = np.divide(boxes, input_shape, dtype=np.float32) boxes *= np.array([image_shape[1], image_shape[0], image_shape[1], image_shape[0]])
return boxes
mean = np.array([0.485, 0.456, 0.406], dtype=np.float32)std = np.array([0.229, 0.224, 0.225], dtype=np.float32)
CATEGORY_COLORS = { 0: [0, 0, 0], # Things (Black) 1: [255, 0, 255], # Uterus (Magenta) 2: [0, 75, 150], # BG (Brown)}# 1. Create a color palette array (fast lookup)palette_map = np.zeros((256, 3), dtype=np.uint8)for i, color in CATEGORY_COLORS.items(): palette_map[i] = color
@spaces.GPUdef predict_image(img_path): img = cv2.imread(img_path) if img is None: raise FileNotFoundError(f"Image not found at {img_path}")
img_resized = cv2.resize(img, (512, 512)) img_input = img_resized[:, :, ::-1].astype(np.float32) / 255.0 img_input = (img_input - mean) / std img_input = img_input.transpose(2, 0, 1)[np.newaxis, :] # (1, 3, H, W)
session = onnxruntime.InferenceSession("deeplabv3_r50_best_Pan.onnx", providers=["CUDAExecutionProvider", 'CPUExecutionProvider']) input_name = session.get_inputs()[0].name
outputs = session.run(None, {input_name: img_input}) # Initialize YOLOv26 Instance Segmentator yoloseg = YOLOSeg("best.onnx", conf_thres=0.3) # Detect Objects yoloseg(img)
orig_h, orig_w = img.shape[:2]
mask = np.argmax(outputs[0].squeeze(), axis=0).astype(np.uint8) color_mask = palette_map[mask] # Instant mapping
color_mask = cv2.resize(color_mask, (orig_w, orig_h)) overlay = cv2.addWeighted(img, 0.3, color_mask, 0.7, 0) # Draw detections annotated_image_bgr = yoloseg.draw_masks(overlay) # annotated_image_bgr = overlay annotated_image_rgb = annotated_image_bgr[..., ::-1] return Image.fromarray(annotated_image_rgb)
nyiapp = gr.Interface( fn=predict_image, inputs=gr.Image(type="filepath", label="Upload an Image"), outputs=gr.Image(type="pil", label="Results Image"), title="3D Chair Detection using KeypointRCNN", description="Torchvision KeypointRCNN 3D Chair Detection.",
examples=["sample1.jpg", "sample2.jpg", "sample3.jpg", "sample4.jpg"])
nyiapp.launch()123version https://git-lfs.github.com/spec/v1oid sha256:487d6392f6ed8de1e09e2f4af267c0f5b2b92c50d6cd9809d943bf9dd7f223f9size 2369195761234567gradiopillowspacesonnxonnxruntimeopencv-pythonnumpyapp.pyAdded+283
keypointrcnn_3d_chair.onnxAdded+3
requirements.txtAdded+7
sample1.jpgAdded

sample2.jpgAdded

sample3.jpgAdded

sample4.jpgAdded
