Nyi2025's picture
Update app.py
3aab974 verified
Raw History Blame Contribute Delete
9.85 kB
# app.py
import gradio as gr
from PIL import Image
import spaces
import onnxruntime
import numpy as np
import cv2
import torch
from torchvision.ops import nms
conf_thr = 0.3
pairs = [
[0, 1], [1, 2],
[2, 3], [3, 0],
[0, 4], [1, 5],
[2, 6], [3, 7],
[8, 9],
[4, 5], [5, 6],
[6, 7], [7, 4],
[8, 7], [9, 6],
]
max_height = 500
max_width = 500
def enlarge_surface(points, scale=1.2):
"""Scale a quadrilateral surface outward from its center."""
center = np.mean(points, axis=0)
vectors = points - center
enlarged_pts = center + vectors * scale
return enlarged_pts
def draw_3d_box_whole_body_from_kpts(image, kpts_scaled, color=(0, 0, 255), thickness=2, scale=1.4):
"""
Draws an enlarged extended whole-body cube from ONNX keypoints.
- Enlarges bottom & top base surfaces.
- Connects bottom directly to extended top.
"""
# Must have points 1-10
if len(kpts_scaled) < 10 or any(kpts_scaled[pt_id-1] is None for pt_id in range(1, 11)):
return image
# Bottom face (points 1-4)
bottom_pts = np.array([kpts_scaled[pt_id-1] for pt_id in range(1, 5)])
bottom_pts = enlarge_surface(bottom_pts, scale=scale)
# Top base (points 5-8)
top_base_pts = np.array([kpts_scaled[pt_id-1] for pt_id in range(5, 9)])
top_base_pts = enlarge_surface(top_base_pts, scale=scale)
# Backrest top points (9,10)
top_pt9 = np.array(kpts_scaled[8])
top_pt10 = np.array(kpts_scaled[9])
top_back = (top_pt9 + top_pt10) / 2
# Height vector
top_base_back = np.mean(top_base_pts[2:4], axis=0) # points 7 and 8
height_vector = top_back - top_base_back
# Extended top face
extended_top_pts = top_base_pts + height_vector
# Convert to int tuples
bottom_int = [(int(x), int(y)) for x, y in bottom_pts]
extended_top_int = [(int(x), int(y)) for x, y in extended_top_pts]
# Draw bottom face
for i in range(4):
cv2.line(image, bottom_int[i], bottom_int[(i + 1) % 4], color, thickness, lineType=cv2.LINE_AA)
# Draw extended top face
for i in range(4):
cv2.line(image, extended_top_int[i], extended_top_int[(i + 1) % 4], color, thickness, lineType=cv2.LINE_AA)
# Draw vertical edges (bottom → extended top)
for i in range(4):
cv2.line(image, bottom_int[i], extended_top_int[i], color, thickness, lineType=cv2.LINE_AA)
return image
def draw_3d_box_whole_body_from_kpts_color(
image,
kpts_scaled,
thickness=2,
scale=1.4,
alpha_top=0.5,
alpha_sides=0.1,
alpha_bottom=0.5
):
if len(kpts_scaled) < 10 or any(kpts_scaled[pt_id-1] is None for pt_id in range(1, 11)):
return image
bottom_pts = np.array([kpts_scaled[pt_id-1] for pt_id in range(1, 5)])
bottom_pts = enlarge_surface(bottom_pts, scale=scale)
top_base_pts = np.array([kpts_scaled[pt_id-1] for pt_id in range(5, 9)])
top_base_pts = enlarge_surface(top_base_pts, scale=scale)
top_pt9 = np.array(kpts_scaled[8])
top_pt10 = np.array(kpts_scaled[9])
top_back = (top_pt9 + top_pt10) / 2
top_base_back = np.mean(top_base_pts[2:4], axis=0)
height_vector = top_back - top_base_back
extended_top_pts = top_base_pts + height_vector
bottom_int = np.array([(int(x), int(y)) for x, y in bottom_pts], dtype=np.int32)
ext_top_int = np.array([(int(x), int(y)) for x, y in extended_top_pts], dtype=np.int32)
faces = [
(ext_top_int, (0, 255, 255), "top"),
(np.array([bottom_int[0], bottom_int[1], ext_top_int[1], ext_top_int[0]]), (0, 255, 0), "side"), # FRONT
(np.array([bottom_int[1], bottom_int[2], ext_top_int[2], ext_top_int[1]]), (0, 255, 0), "side"), # RIGHT
(np.array([bottom_int[2], bottom_int[3], ext_top_int[3], ext_top_int[2]]), (0, 255, 0), "side"), # BACK
(np.array([bottom_int[3], bottom_int[0], ext_top_int[0], ext_top_int[3]]), (0, 255, 0), "side"), # LEFT
(bottom_int, (255, 0, 0), "bottom")
]
img_float = image.astype(np.float32)
for face_pts, face_color, face_type in faces:
mask = np.zeros(image.shape[:2], dtype=np.uint8)
cv2.fillPoly(mask, [face_pts], 255)
if mask.sum() == 0:
continue
if face_type == "top":
alpha = alpha_top
elif face_type == "bottom":
alpha = alpha_bottom
else:
alpha = alpha_sides
color_arr = np.array(face_color, dtype=np.float32).reshape(1, 1, 3)
mask_bool = mask.astype(bool)
dst_pixels = img_float[mask_bool]
blended = dst_pixels * (1.0 - alpha) + color_arr * alpha
img_float[mask_bool] = blended
image = np.clip(img_float, 0, 255).astype(np.uint8)
# Draw edges with the requested colors:
for i in range(4):
# Bottom face edges - green
cv2.line(image, tuple(bottom_int[i]), tuple(bottom_int[(i + 1) % 4]), (0, 255, 0), thickness, lineType=cv2.LINE_AA)
# Top face edges - green
cv2.line(image, tuple(ext_top_int[i]), tuple(ext_top_int[(i + 1) % 4]), (0, 255, 0), thickness, lineType=cv2.LINE_AA)
# Vertical edges (bottom to top) with per-face colors:
# Front face vertical edges (bottom_int[0], ext_top_int[0]) and (bottom_int[1], ext_top_int[1]) => yellow
cv2.line(image, tuple(bottom_int[0]), tuple(ext_top_int[0]), (255, 255, 0), thickness, lineType=cv2.LINE_AA) # Yellow
cv2.line(image, tuple(bottom_int[1]), tuple(ext_top_int[1]), (255, 255, 0), thickness, lineType=cv2.LINE_AA) # Yellow
# Back face vertical edges (bottom_int[2], ext_top_int[2]) and (bottom_int[3], ext_top_int[3]) => green
cv2.line(image, tuple(bottom_int[2]), tuple(ext_top_int[2]), (0, 255, 0), thickness, lineType=cv2.LINE_AA) # White
cv2.line(image, tuple(bottom_int[3]), tuple(ext_top_int[3]), (0, 255, 0), thickness, lineType=cv2.LINE_AA) # White
return image
@spaces.GPU
def 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, (640, 480))
img_input = img_resized.astype(np.float32) / 255.0
img_input = img_input.transpose(2, 0, 1)[np.newaxis, :] # (1, 3, H, W)
session = onnxruntime.InferenceSession("keypointrcnn_3d_chair.onnx", providers=["CUDAExecutionProvider", 'CPUExecutionProvider'])
input_name = session.get_inputs()[0].name
outputs = session.run(None, {input_name: img_input})
boxes, labels, scores, keypoints, kp_scores = outputs
# Convert to numpy arrays
boxes = np.array(boxes)
scores = np.array(scores)
keypoints = np.array(keypoints)
kp_scores = np.array(kp_scores)
# Apply NMS
boxes_tensor = torch.tensor(boxes, dtype=torch.float32)
scores_tensor = torch.tensor(scores, dtype=torch.float32)
keep = nms(boxes_tensor, scores_tensor, iou_threshold=0.3)
boxes = boxes_tensor[keep].numpy()
scores = scores_tensor[keep].numpy()
keypoints = keypoints[keep]
kp_scores = kp_scores[keep]
# Minimal fix: if only one detection, ensure keypoints and kp_scores have batch dimension
if len(boxes) == 1:
if keypoints.ndim == 2: # shape (10, 3) instead of (1, 10, 3)
keypoints = keypoints[np.newaxis, ...]
if kp_scores.ndim == 1: # shape (10,) instead of (1, 10)
kp_scores = kp_scores[np.newaxis, ...]
# Resize back to original scale
h_orig, w_orig = img.shape[:2]
scale_x = w_orig / 640 # width scale
scale_y = h_orig / 480 # height scale careful: dummy input was (480, 640)
img_vis = cv2.cvtColor(img.copy(), cv2.COLOR_BGR2RGB)
img_skeleton_only = np.zeros_like(img_vis) # black image same size as original
# Store scaled keypoints
all_kpts_scaled = []
for i in range(len(scores)):
if scores[i] < conf_thr:
continue
# Draw bounding box
x1, y1, x2, y2 = boxes[i]
x1 = int(x1 * scale_x)
y1 = int(y1 * scale_y)
x2 = int(x2 * scale_x)
y2 = int(y2 * scale_y)
x1 = max(0, min(x1, w_orig - 1))
y1 = max(0, min(y1, h_orig - 1))
x2 = max(0, min(x2, w_orig - 1))
y2 = max(0, min(y2, h_orig - 1))
# cv2.rectangle(img_vis, (x1, y1), (x2, y2), (255, 255, 0), 2)
# cv2.rectangle(img_skeleton_only, (x1, y1), (x2, y2), (255, 255, 0), 2)
# Scale keypoints
kpts_scaled = []
for k in range(keypoints.shape[1]):
kpt = keypoints[i][k]
# Make sure it's at least a 1D array
if np.ndim(kpt) == 1 and kpt.shape[0] >= 2:
kx, ky = kpt[0], kpt[1]
else:
kpts_scaled.append(None)
continue
# Score check
if kp_scores[i][k] > 0.3:
kx = int(kx * scale_x)
ky = int(ky * scale_y)
kpts_scaled.append((kx, ky))
else:
kpts_scaled.append(None)
all_kpts_scaled.append(kpts_scaled)
# Draw whole-body 3D cube box
# img_vis = draw_3d_box_whole_body_from_kpts(img_vis, kpts_scaled, color=(0, 255, 0), thickness=3)
img_vis = draw_3d_box_whole_body_from_kpts_color(img_vis, kpts_scaled, thickness=3)
annotated_image_bgr = img_vis
# annotated_image_rgb = annotated_image_bgr[..., ::-1]
return Image.fromarray(annotated_image_bgr)
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()