Spaces:
Running on T4
Running on T4
Download baseball_batting/bat2d.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 4.31 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/baseball_batting/bat2d.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/baseball_batting/bat2d.py
-
curl -L -o bat2d.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/baseball_batting/bat2d.py
4.31 kB
| """Contour and optical-flow proposals. Boxes never become measured endpoints.""" | |
| import cv2 | |
| import numpy as np | |
| def contour_endpoints(image, box, previous=None): | |
| h, w = image.shape[:2] | |
| x1, y1, x2, y2 = np.rint(box).astype(int) | |
| x1, y1, x2, y2 = max(0, x1), max(0, y1), min(w, x2), min(h, y2) | |
| if x2-x1 < 8 or y2-y1 < 8: | |
| return None | |
| roi = image[y1:y2, x1:x2] | |
| mask = np.zeros(roi.shape[:2], np.uint8) | |
| bg, fg = np.zeros((1, 65), np.float64), np.zeros((1, 65), np.float64) | |
| cv2.grabCut(roi, mask, (1, 1, roi.shape[1]-2, roi.shape[0]-2), bg, fg, 2, cv2.GC_INIT_WITH_RECT) | |
| foreground = np.where((mask == 1) | (mask == 3), 255, 0).astype(np.uint8) | |
| contours, _ = cv2.findContours(foreground, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) | |
| options = [] | |
| for c in contours: | |
| points = c.reshape(-1, 2).astype(float) | |
| if len(points) < 8: | |
| continue | |
| vx, vy, ax, ay = cv2.fitLine(c, cv2.DIST_HUBER, 0, .01, .01).ravel() | |
| axis = np.array([vx, vy]); origin = np.array([ax, ay]) | |
| along = (points-origin) @ axis | |
| across = (points-origin) @ np.array([-vy, vx]) | |
| length, width = np.ptp(along), np.ptp(across) | |
| if length < 20 or length / max(width, 1) < 4: | |
| continue | |
| ends = origin + np.array([[along.min()], [along.max()]])*axis + [x1, y1] | |
| # Reject contours truncated by the ROI: true ends are not visible. | |
| if np.any(points[:, 0] < 2) or np.any(points[:, 0] > roi.shape[1]-3) or np.any(points[:, 1] < 2) or np.any(points[:, 1] > roi.shape[0]-3): | |
| continue | |
| options.append((length, ends)) | |
| if len(options) != 1 or previous is None: | |
| return None # Endpoint identity needs a seed, not an arbitrary left/right choice. | |
| ends = options[0][1] | |
| if np.linalg.norm(ends-np.array(previous)) > np.linalg.norm(ends[::-1]-np.array(previous)): | |
| ends = ends[::-1] | |
| return ends | |
| class BatTracker: | |
| def __init__(self, state=None): | |
| self.points = None if not state or not state.get("points") else np.array(state["points"], dtype=np.float32) | |
| self.previous_gray = None | |
| def snapshot(self): | |
| return {"points": None if self.points is None else self.points.tolist()} | |
| def update(self, image, proposals, manual=None): | |
| gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) | |
| result = {"points": None, "states": ["unknown", "unknown"], "method": "no_supported_endpoints"} | |
| if manual is not None: | |
| self.points = np.array(manual, np.float32) | |
| result = {"points": self.points.tolist(), "states": ["manual", "manual"], "method": "reviewed_seed"} | |
| else: | |
| boxes = [d["box"] for d in proposals if d["class_id"] == 34] | |
| fitted = None | |
| if self.points is not None and len(boxes) == 1: | |
| try: | |
| fitted = contour_endpoints(image, boxes[0], self.points) | |
| except cv2.error: | |
| pass | |
| if fitted is not None: | |
| self.points = fitted.astype(np.float32) | |
| result = {"points": fitted.tolist(), "states": ["image_supported"]*2, "method": "seeded_contour_axis"} | |
| elif self.points is not None and self.previous_gray is not None: | |
| seed = self.points.reshape(-1, 1, 2) | |
| forward, ok, _ = cv2.calcOpticalFlowPyrLK(self.previous_gray, gray, seed, None) | |
| if forward is not None: | |
| backward, back_ok, _ = cv2.calcOpticalFlowPyrLK(gray, self.previous_gray, forward, None) | |
| consistent = backward is not None and np.all(ok) and np.all(back_ok) and np.max(np.linalg.norm(backward-seed, axis=2)) < 1.5 | |
| points = forward.reshape(2, 2) | |
| in_bounds = np.all(points >= 0) and np.all(points[:, 0] < gray.shape[1]) and np.all(points[:, 1] < gray.shape[0]) | |
| if consistent and in_bounds: | |
| self.points = points | |
| result = {"points": points.tolist(), "states": ["propagated"]*2, "method": "LK_forward_backward_proposal"} | |
| else: | |
| self.points = None | |
| else: | |
| self.points = None | |
| self.previous_gray = gray | |
| return result | |