Spaces:
Sleeping
Sleeping
Download pipe_counter/inference.py from npisb/PIPECOUNTv2: direct link, hf CLI and curl.
- Browser
- Download file 8.11 kB
-
https://huggingface.co/spaces/npisb/PIPECOUNTv2/resolve/main/pipe_counter/inference.py
- Command line
-
hf download hf://spaces/npisb/PIPECOUNTv2/pipe_counter/inference.py
-
curl -L -o inference.py https://huggingface.co/spaces/npisb/PIPECOUNTv2/resolve/main/pipe_counter/inference.py
8.11 kB
| from __future__ import annotations | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import List, Optional, Sequence, Tuple, Union | |
| import cv2 | |
| import numpy as np | |
| import onnxruntime as ort | |
| from PIL import Image | |
| ArrayLike = Union[str, Path, Image.Image, np.ndarray] | |
| _PALETTE = [ | |
| (46, 204, 113), | |
| (52, 152, 219), | |
| (231, 76, 60), | |
| (155, 89, 182), | |
| (241, 196, 15), | |
| ] | |
| class Detection: | |
| box: Tuple[int, int, int, int] | |
| confidence: float | |
| label: str | |
| class_id: int | |
| def _sigmoid(x: np.ndarray) -> np.ndarray: | |
| return 1.0 / (1.0 + np.exp(-x)) | |
| def _xywh_to_xyxy(boxes: np.ndarray) -> np.ndarray: | |
| xyxy = boxes.copy() | |
| xyxy[:, 0] = boxes[:, 0] - boxes[:, 2] / 2.0 | |
| xyxy[:, 1] = boxes[:, 1] - boxes[:, 3] / 2.0 | |
| xyxy[:, 2] = boxes[:, 0] + boxes[:, 2] / 2.0 | |
| xyxy[:, 3] = boxes[:, 1] + boxes[:, 3] / 2.0 | |
| return xyxy | |
| def _letterbox( | |
| image: np.ndarray, | |
| new_shape: Tuple[int, int] = (640, 640), | |
| color: Tuple[int, int, int] = (114, 114, 114), | |
| ) -> Tuple[np.ndarray, Tuple[float, float], Tuple[float, float]]: | |
| shape = image.shape[:2] | |
| if isinstance(new_shape, int): | |
| new_shape = (new_shape, new_shape) | |
| r = min(new_shape[0] / shape[0], new_shape[1] / shape[1]) | |
| r = min(r, 1.0) | |
| ratio = (r, r) | |
| new_unpad = (int(round(shape[1] * r)), int(round(shape[0] * r))) | |
| dw = new_shape[1] - new_unpad[0] | |
| dh = new_shape[0] - new_unpad[1] | |
| dw /= 2 | |
| dh /= 2 | |
| if new_unpad != (shape[1], shape[0]): | |
| image = cv2.resize(image, new_unpad, interpolation=cv2.INTER_LINEAR) | |
| top = int(round(dh - 0.1)) | |
| bottom = int(round(dh + 0.1)) | |
| left = int(round(dw - 0.1)) | |
| right = int(round(dw + 0.1)) | |
| image = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) | |
| return image, ratio, (dw, dh) | |
| def _iou(box: np.ndarray, boxes: np.ndarray) -> np.ndarray: | |
| if not len(boxes): | |
| return np.empty((0,), dtype=np.float32) | |
| x1 = np.maximum(box[0], boxes[:, 0]) | |
| y1 = np.maximum(box[1], boxes[:, 1]) | |
| x2 = np.minimum(box[2], boxes[:, 2]) | |
| y2 = np.minimum(box[3], boxes[:, 3]) | |
| inter = np.maximum(0.0, x2 - x1) * np.maximum(0.0, y2 - y1) | |
| box_area = (box[2] - box[0]) * (box[3] - box[1]) | |
| boxes_area = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1]) | |
| union = box_area + boxes_area - inter + 1e-9 | |
| return inter / union | |
| def _nms(boxes: np.ndarray, scores: np.ndarray, iou_thres: float, max_det: int) -> List[int]: | |
| if not len(boxes): | |
| return [] | |
| idxs = scores.argsort()[::-1] | |
| keep: List[int] = [] | |
| while idxs.size > 0 and len(keep) < max_det: | |
| i = idxs[0] | |
| keep.append(int(i)) | |
| if idxs.size == 1: | |
| break | |
| ious = _iou(boxes[i], boxes[idxs[1:]]) | |
| idxs = idxs[1:][ious < iou_thres] | |
| return keep | |
| class PipeCounter: | |
| def __init__( | |
| self, | |
| model_path: Union[str, Path] = Path("model/best.onnx"), | |
| providers: Optional[Sequence[str]] = None, | |
| confidence_threshold: float = 0.45, | |
| iou_threshold: float = 0.45, | |
| image_size: int = 640, | |
| max_detections: int = 300, | |
| ) -> None: | |
| self.model_path = Path(model_path) | |
| if not self.model_path.exists(): | |
| raise FileNotFoundError(f"Model file not found: {self.model_path}") | |
| self.confidence_threshold = confidence_threshold | |
| self.iou_threshold = iou_threshold | |
| self.image_size = image_size | |
| self.max_detections = max_detections | |
| self.session = ort.InferenceSession(str(self.model_path), providers=providers or ["CPUExecutionProvider"]) | |
| self.input_name = self.session.get_inputs()[0].name | |
| meta = self.session.get_modelmeta().custom_metadata_map | |
| self.labels = self._parse_labels(meta.get("names", "{0: 'pipe'}")) | |
| self.num_classes = max(len(self.labels), 1) | |
| def _parse_labels(raw: str) -> List[str]: | |
| try: | |
| mapping = eval(raw) | |
| return [mapping.get(i, f"class_{i}") for i in sorted(mapping)] | |
| except Exception: | |
| return ["pipe"] | |
| def _to_numpy(self, data: ArrayLike) -> np.ndarray: | |
| if isinstance(data, np.ndarray): | |
| if data.ndim == 2: | |
| data = np.stack([data] * 3, axis=-1) | |
| if data.shape[2] == 4: | |
| data = data[:, :, :3] | |
| return data | |
| if isinstance(data, (str, Path)): | |
| data = Image.open(data) | |
| if isinstance(data, Image.Image): | |
| data = data.convert("RGB") | |
| return np.array(data) | |
| raise TypeError("Unsupported input type for image data") | |
| def _prepare(self, image: np.ndarray) -> Tuple[np.ndarray, Tuple[float, float], Tuple[float, float]]: | |
| image_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) | |
| processed, ratio, pad = _letterbox(image_bgr, (self.image_size, self.image_size)) | |
| processed = processed.astype(np.float32) / 255.0 | |
| processed = np.transpose(processed, (2, 0, 1)) | |
| processed = np.expand_dims(processed, axis=0) | |
| return processed, ratio, pad | |
| def predict( | |
| self, | |
| data: ArrayLike, | |
| confidence: Optional[float] = None, | |
| iou: Optional[float] = None, | |
| ) -> Tuple[List[Detection], Image.Image]: | |
| conf_thres = confidence if confidence is not None else self.confidence_threshold | |
| iou_thres = iou if iou is not None else self.iou_threshold | |
| image = self._to_numpy(data) | |
| original = image.copy() | |
| blob, ratio, pad = self._prepare(image) | |
| outputs = self.session.run(None, {self.input_name: blob})[0] | |
| preds = outputs[0] | |
| preds = preds.reshape(preds.shape[0], -1) | |
| boxes = preds[:4, :].T | |
| class_scores = preds[4:, :] | |
| if class_scores.size == 0: | |
| class_scores = np.zeros((1, boxes.shape[0]), dtype=np.float32) | |
| class_scores = _sigmoid(class_scores).T | |
| boxes = _xywh_to_xyxy(boxes) | |
| boxes[:, [0, 2]] -= pad[0] | |
| boxes[:, [1, 3]] -= pad[1] | |
| boxes[:, [0, 2]] /= ratio[0] | |
| boxes[:, [1, 3]] /= ratio[1] | |
| boxes[:, 0] = np.clip(boxes[:, 0], 0, original.shape[1]) | |
| boxes[:, 1] = np.clip(boxes[:, 1], 0, original.shape[0]) | |
| boxes[:, 2] = np.clip(boxes[:, 2], 0, original.shape[1]) | |
| boxes[:, 3] = np.clip(boxes[:, 3], 0, original.shape[0]) | |
| class_ids = class_scores.argmax(axis=1) | |
| scores = class_scores.max(axis=1) | |
| mask = scores >= conf_thres | |
| boxes = boxes[mask] | |
| scores = scores[mask] | |
| class_ids = class_ids[mask] | |
| if not len(scores): | |
| annotated = self._draw(original, []) | |
| return [], annotated | |
| keep = _nms(boxes, scores, iou_thres, self.max_detections) | |
| detections = [ | |
| Detection( | |
| box=(int(boxes[i][0]), int(boxes[i][1]), int(boxes[i][2]), int(boxes[i][3])), | |
| confidence=float(scores[i]), | |
| label=self.labels[class_ids[i]] if class_ids[i] < len(self.labels) else f"class_{class_ids[i]}", | |
| class_id=int(class_ids[i]), | |
| ) | |
| for i in keep | |
| ] | |
| annotated = self._draw(original, detections) | |
| return detections, annotated | |
| def _draw(self, image: np.ndarray, detections: Sequence[Detection]) -> Image.Image: | |
| canvas = image.copy() | |
| canvas = cv2.cvtColor(canvas, cv2.COLOR_RGB2BGR) | |
| for det in detections: | |
| x1, y1, x2, y2 = det.box | |
| color = _PALETTE[det.class_id % len(_PALETTE)] | |
| cv2.rectangle(canvas, (x1, y1), (x2, y2), color, 2) | |
| label = f"{det.label} {det.confidence:.2f}" | |
| (tw, th), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1) | |
| cv2.rectangle(canvas, (x1, max(0, y1 - th - 6)), (x1 + tw + 2, y1), color, -1) | |
| cv2.putText(canvas, label, (x1 + 1, max(12, y1 - 4)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1, cv2.LINE_AA) | |
| canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB) | |
| return Image.fromarray(canvas) | |