Narrow Vision Detector Backends

This commit is contained in:
firestar5683
2026-11-28 16:03:36 -06:00
parent 6fe3b9aad5
commit ba84f072bb
3 changed files with 55 additions and 19 deletions
@@ -269,6 +269,8 @@ class HistoryEntry:
strong_consensus: bool = False
def _primary_regulatory_panel(image):
if cv2 is None:
raise RuntimeError('OpenCV is required for vision inference')
height, width = image.shape[:2]
if image.dtype != np.uint8 or width < 24 or height < 1.8 * width:
return image
@@ -357,6 +359,8 @@ class VisionModelCore:
@classmethod
def _load_net(cls, name: str, expected_sha256: str):
if cv2 is None:
raise RuntimeError('OpenCV is required for vision inference')
path = cls._verified_model_path(name, expected_sha256)
net = cv2.dnn.readNetFromONNX(str(path))
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)
@@ -421,6 +425,8 @@ class VisionModelCore:
@staticmethod
def _letterbox(image, shape=(640, 640), color=(114, 114, 114)):
if cv2 is None:
raise RuntimeError('OpenCV is required for vision inference')
image_height, image_width = image.shape[:2]
ratio = min(shape[0] / image_height, shape[1] / image_width)
resized_width = int(round(image_width * ratio))
@@ -461,6 +467,8 @@ class VisionModelCore:
@staticmethod
def _is_yellow_advisory(sign_crop):
if cv2 is None:
raise RuntimeError('OpenCV is required for vision inference')
if sign_crop.size == 0:
return False
sign_crop = _primary_regulatory_panel(sign_crop)
@@ -475,6 +483,8 @@ class VisionModelCore:
def _is_regulatory_speed_sign(self, sign_crop):
if cv2 is None:
raise RuntimeError('OpenCV is required for vision inference')
if sign_crop.size == 0:
return False
@@ -596,6 +606,8 @@ class VisionModelCore:
@staticmethod
def _square_resize(image, size=128, color=(114, 114, 114)):
if cv2 is None:
raise RuntimeError('OpenCV is required for vision inference')
image_height, image_width = image.shape[:2]
ratio = min(size / max(image_height, 1), size / max(image_width, 1))
resized_width = max(int(round(image_width * ratio)), 1)
@@ -636,6 +648,8 @@ class VisionModelCore:
def _forward_detector_region(self, frame_bgr):
if cv2 is None:
raise RuntimeError('OpenCV is required for vision inference')
detector_shape = (self.detector_input_size, self.detector_input_size)
letterboxed, ratio, pad_width, pad_height = self._letterbox(frame_bgr, shape=detector_shape)
blob = cv2.dnn.blobFromImage(letterboxed, scalefactor=1 / 255.0, size=detector_shape, swapRB=True, crop=False)
@@ -747,6 +761,8 @@ class VisionModelCore:
def _classify_speed_limit_from_model(self, sign_crop):
if cv2 is None:
raise RuntimeError('OpenCV is required for vision inference')
self.last_classifier_advisory_rejected = False
self.last_classifier_reject_dominant = False
if self.classifier_net is None or sign_crop.size == 0:
@@ -1013,7 +1029,7 @@ class VisionModelCore:
proposal_area_ratio <= DETECTOR_CLASSIFIER_TRUSTED_MODEL_MAX_AREA_RATIO and
proposal_confidence >= DETECTOR_CLASSIFIER_TRUSTED_MODEL_MIN_PROPOSAL_CONFIDENCE)):
from openpilot.starpilot.speed_limits.vision.speed_face import SpeedFaceVerifier, SharedSpeedFaceVerifier
if (type(face_filter) in (SpeedFaceVerifier, SharedSpeedFaceVerifier) and
if (face_filter is not None and type(face_filter) in (SpeedFaceVerifier, SharedSpeedFaceVerifier) and
getattr(face_filter.reject_once, '__func__', None) is SpeedFaceVerifier.reject_once and
face_filter._checked is True and
getattr(self._is_regulatory_speed_sign, '__func__', None) is
@@ -58,6 +58,8 @@ def crop(np, cv2, rgb256, box):
def warning_context_box(rgb256, box):
if cv2 is None:
raise RuntimeError('OpenCV is required for vision inference')
from openpilot.starpilot.speed_limits.vision import model
image = np.rint(rgb256.transpose(1, 2, 0) * np.float32(255)).astype(np.uint8)
@@ -92,6 +94,8 @@ def warning_context_box(rgb256, box):
def inset_context_box(rgb256, box):
if cv2 is None:
raise RuntimeError('OpenCV is required for vision inference')
image = np.rint(rgb256.transpose(1, 2, 0) * np.float32(255)).astype(np.uint8)
edges = cv2.Canny(cv2.cvtColor(image, cv2.COLOR_RGB2GRAY), 30, 90)
edges = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8))
@@ -201,6 +205,8 @@ class SpeedFaceVerifier:
started = time.monotonic()
self.last_forward_count += 1
try:
if self.net is None:
raise RuntimeError('The speed-face verifier is closed')
self.net.setInput(patch[None])
output = self.net.forward(['speed_face_logit'])[0]
if output.shape != (1, 1) or output.dtype != np.float32 or not np.isfinite(output).all():
@@ -13,24 +13,25 @@ from openpilot.starpilot.speed_limits.vision.stop_signs import StopDetection, Ca
def left_panel_region(image):
height, width = image.shape[:2]
if image.dtype != np.uint8 or height < 32 or width < 128:
cv2 = model.cv2
if cv2 is None or image.dtype != np.uint8 or height < 32 or width < 128:
return None
left, right = int(width * .35), int(width * .45)
top, bottom = int(height * .15), int(height * .70)
hsv = model.cv2.cvtColor(image[top:bottom, left:right], model.cv2.COLOR_BGR2HSV)
gray = model.cv2.cvtColor(image[top:bottom, left:right], model.cv2.COLOR_BGR2GRAY)
edges = model.cv2.morphologyEx(model.cv2.Canny(gray, 20, 60), model.cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8))
contours, _ = model.cv2.findContours(edges, model.cv2.RETR_LIST, model.cv2.CHAIN_APPROX_SIMPLE)
hsv = cv2.cvtColor(image[top:bottom, left:right], cv2.COLOR_BGR2HSV)
gray = cv2.cvtColor(image[top:bottom, left:right], cv2.COLOR_BGR2GRAY)
edges = cv2.morphologyEx(cv2.Canny(gray, 20, 60), cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8))
contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
matches = []
for contour in contours:
x, y, w, h = model.cv2.boundingRect(contour)
x, y, w, h = cv2.boundingRect(contour)
if not (14 <= w <= width * .08 and 18 <= h <= height * .20 and .4 <= w / h <= 1.5):
continue
contour = model.cv2.convexHull(contour)
if top + y + h / 2 > height * .55 or model.cv2.contourArea(contour) < w * h * .75:
contour = cv2.convexHull(contour)
if top + y + h / 2 > height * .55 or cv2.contourArea(contour) < w * h * .75:
continue
quad = model.cv2.approxPolyDP(contour, .02 * model.cv2.arcLength(contour, True), True)
if not 4 <= len(quad) <= 6 or not model.cv2.isContourConvex(quad):
quad = cv2.approxPolyDP(contour, .02 * cv2.arcLength(contour, True), True)
if not 4 <= len(quad) <= 6 or not cv2.isContourConvex(quad):
continue
patch = hsv[y:y + h, x:x + w]
dark = (patch[:, :, 2] <= model.REGULATORY_DARK_VALUE_MAX) & (patch[:, :, 1] <= model.REGULATORY_DARK_SAT_MAX)
@@ -54,13 +55,14 @@ def left_panel_region(image):
def feedback_panel_region(image):
height, width = image.shape[:2]
if image.dtype != np.uint8 or min(height, width) < 384:
cv2 = model.cv2
if cv2 is None or image.dtype != np.uint8 or min(height, width) < 384:
return None
left, bottom = int(width * .45), int(height * .65)
hsv = model.cv2.cvtColor(image[:bottom, left:], model.cv2.COLOR_BGR2HSV)
amber = model.cv2.inRange(hsv, np.array((5, 160, 120)), np.array((35, 255, 255)))
joined = model.cv2.morphologyEx(amber, model.cv2.MORPH_CLOSE, np.ones((21, 21), np.uint8))
_, _, stats, _ = model.cv2.connectedComponentsWithStats(joined)
hsv = cv2.cvtColor(image[:bottom, left:], cv2.COLOR_BGR2HSV)
amber = cv2.inRange(hsv, np.array((5, 160, 120)), np.array((35, 255, 255)))
joined = cv2.morphologyEx(amber, cv2.MORPH_CLOSE, np.ones((21, 21), np.uint8))
_, _, stats, _ = cv2.connectedComponentsWithStats(joined)
matches = []
for x, y, w, h, area in stats[1:]:
if (8 <= w <= 160 and 5 <= h <= 100 and .8 <= w / h <= 4 and
@@ -107,7 +109,10 @@ class TrafficSignModelCore(model.VisionModelCore):
def set_speed_enabled(self, enabled):
if enabled == self.speed_enabled:
return
new_face = SharedSpeedFaceVerifier(self._stop_face_filter.net) if enabled else None
new_face = None
if enabled:
assert self._stop_face_filter is not None
new_face = SharedSpeedFaceVerifier(self._stop_face_filter.net)
try:
detector = self._detector_for_mode(enabled)
classifier = self._load_net("speed_limit_us_value_classifier.onnx", self.CLASSIFIER_SHA256) if enabled else None
@@ -149,6 +154,7 @@ class TrafficSignModelCore(model.VisionModelCore):
self.net.rgb256 = None
def infer(self, frame_bgr: np.ndarray) -> model.Detection | None:
assert self._stop_face_filter is not None
self._stop_face_filter.begin_frame()
self.stop_detections = ()
try:
@@ -189,6 +195,7 @@ class TrafficSignModelCore(model.VisionModelCore):
region = feedback[0] if feedback is not None else left_panel_region(frame_bgr)
if region is not None:
face = self._speed_face_filter
assert face is not None
count, elapsed = face.last_forward_count, face.last_forward_duration_s
face.begin_frame()
try:
@@ -217,6 +224,7 @@ class TrafficSignModelCore(model.VisionModelCore):
return None
candidate, rgb, raw, index = record
face = self._speed_face_filter
assert face is not None
count, elapsed = face.last_forward_count, face.last_forward_duration_s
face.begin_frame()
self._tiny_recovery = True
@@ -250,7 +258,10 @@ class TrafficSignModelCore(model.VisionModelCore):
candidates.append(((confidence, 0, (x1, y1, x2, y2)), self.net.rgb256, speed[0, :4, index].copy(), int(index)))
boxes.append((x1, y1, w, h))
scores.append(confidence)
keep = np.asarray(model.cv2.dnn.NMSBoxes(boxes, scores, .8, .4)).reshape(-1) if boxes else []
keep = []
if boxes:
assert model.cv2 is not None
keep = np.asarray(model.cv2.dnn.NMSBoxes(boxes, scores, .8, .4)).reshape(-1)
self._tiny_candidate = candidates[int(keep[0])] if len(keep) == 1 else None
def _collect_detector_classifier_proposals_from_region(self, frame_bgr, origin_x, origin_y,
@@ -265,13 +276,15 @@ class TrafficSignModelCore(model.VisionModelCore):
if self.net is not None:
height, width = frame_bgr.shape[:2]
ratio = min(self.detector_input_size / height, self.detector_input_size / width)
stop_filter = self._stop_face_filter
assert stop_filter is not None
self.stop_detections += decode_stop_signs(
self.net.stops, ratio=ratio,
pad_width=(self.detector_input_size - round(width * ratio)) / 2,
pad_height=(self.detector_input_size - round(height * ratio)) / 2,
region_width=width, region_height=height, origin_x=origin_x, origin_y=origin_y,
full_frame_width=full_frame_width, full_frame_height=full_frame_height, threshold=self.STOP_THRESHOLD,
accept_dense_id=lambda index: self._stop_face_filter.accept(self.net.rgb256, self.net.stops, index))
accept_dense_id=lambda index: stop_filter.accept(self.net.rgb256, self.net.stops, index))
if getattr(self, 'speed_enabled', True) and model.DETECTOR_CLASSIFIER_REGION_MODE == 'right_roi' and origin_x > 0:
self._capture_small_sign(ratio=ratio, pad_width=(self.detector_input_size - round(width * ratio)) / 2,
pad_height=(self.detector_input_size - round(height * ratio)) / 2,
@@ -315,6 +328,7 @@ class TrafficSignModelCore(model.VisionModelCore):
def _forward_stop_detector_region(self, frame_bgr):
shape = (self.detector_input_size, self.detector_input_size)
letterboxed, _, _, _ = self._letterbox(frame_bgr, shape=shape)
assert model.cv2 is not None
blob = model.cv2.dnn.blobFromImage(letterboxed, scalefactor=1 / 255.0, size=shape, swapRB=True, crop=False)
self.net.setInput(blob)
began = time.monotonic()