diff --git a/camera/chandra-camera b/camera/chandra-camera index cb58317..7cad54d 100755 --- a/camera/chandra-camera +++ b/camera/chandra-camera @@ -4,11 +4,14 @@ import argparse from dataclasses import dataclass import datetime +import fcntl +import glob import mmap import os import queue import shutil import signal +import struct import subprocess import sys import threading @@ -255,6 +258,224 @@ def convert_frame(raw, width, height, stride, fmt, rot=0, cv2_mod=None, np_mod=N return np_mod.ascontiguousarray(rotate_bgr(bgr, rot, cv2_mod)) +VIDIOC_G_CTRL = 0xC008561B +VIDIOC_S_CTRL = 0xC008561C +VIDIOC_QUERYCTRL = 0xC0445624 +V4L2_CID_EXPOSURE = 0x00980911 +V4L2_CID_VBLANK = 0x009E0901 +V4L2_CID_ANALOGUE_GAIN = 0x009E0903 +V4L2_CID_DIGITAL_GAIN = 0x009F0905 + +_QUAD_TONE_LUT = None + + +def _build_tone_lut(np_mod): + """Build 4096-entry uint8 tone LUT: linear 0..160, smooth highlight roll-off to 768, gamma 2.2.""" + x = np_mod.linspace(0.0, 768.0, 4096, dtype=np_mod.float32) + t = np_mod.maximum(x - 160.0, 0.0) / 95.0 + y = np_mod.where(x <= 160.0, x, 160.0 + 95.0 * (t / (1.0 + 0.65 * t))) + y = np_mod.clip(y / 255.0, 0.0, 1.0) + return np_mod.clip((y ** (1.0 / 2.2)) * 255.0, 0, 255).astype(np_mod.uint8) + + +def _get_tone_lut(np_mod): + global _QUAD_TONE_LUT + if _QUAD_TONE_LUT is None: + _QUAD_TONE_LUT = _build_tone_lut(np_mod) + return _QUAD_TONE_LUT + + +def find_sensor_subdev(model): + """Find /dev/v4l-subdevN matching sensor `model`, or None.""" + if not model: + return None + want = model.lower() + for p in sorted(glob.glob("/sys/class/video4linux/v4l-subdev*/name")): + try: + with open(p) as fh: + name = fh.read().strip().lower() + except OSError: + continue + if name == want or name.startswith(want + " "): + return "/dev/" + os.path.basename(os.path.dirname(p)) + return None + + +class _V4L2SubdevIO: + """Thin ioctl wrapper over a V4L2 subdevice file descriptor.""" + + def __init__(self, path): + self.fd = os.open(path, os.O_RDWR) + + def query(self, cid): + buf = bytearray(68) + struct.pack_into("= 0: + try: + os.close(self.fd) + finally: + self.fd = -1 + + +class QuadSensorAE: + """Direct V4L2 subdev auto-exposure and gain controller for Raw-only Quad-Bayer capture.""" + + def __init__(self, subdev_path, io=None): + self.io = io if io is not None else _V4L2SubdevIO(subdev_path) + self._closed = False + try: + self.vb_min, self.vb_max, _, _ = self.io.query(V4L2_CID_VBLANK) + self.exp_min, self.exp_max_now, _, _ = self.io.query(V4L2_CID_EXPOSURE) + self.ag_min, self.ag_max, _, _ = self.io.query(V4L2_CID_ANALOGUE_GAIN) + self.init_vblank = self.io.get(V4L2_CID_VBLANK) + self.init_exp = self.io.get(V4L2_CID_EXPOSURE) + self.init_ag = self.io.get(V4L2_CID_ANALOGUE_GAIN) + try: + self.dg_min, self.dg_max, _, _ = self.io.query(V4L2_CID_DIGITAL_GAIN) + self.init_dg = self.io.get(V4L2_CID_DIGITAL_GAIN) + self.has_dgain = True + except OSError: + self.dg_min, self.dg_max, self.init_dg, self.has_dgain = 1024, 1024, 1024, False + except Exception: + self.io.close() + raise + + self.exp_base_max = max(self.exp_min + 1, self.exp_max_now - max(0, self.init_vblank - self.vb_min)) + self.vb_cap = min(self.vb_max, 9500) + self.exp_lowlight_max = min(self.exp_base_max + max(0, self.vb_cap - self.vb_min), 12000) + self.ag_max_x = 512.0 / max(512 - min(self.ag_max, 504), 1) + self.dg_max_x = min(self.dg_max / 1024.0, 4.0) if self.has_dgain else 1.0 + self.e_min = float(max(20, self.exp_min)) + self.e_max = float(self.exp_lowlight_max) * self.ag_max_x * self.dg_max_x + self.cur_vblank = self.init_vblank + self.cur_exp = self.init_exp + self.cur_ag = self.init_ag + self.cur_dg = self.init_dg + self.ev_total = float(self.exp_base_max) * min(8.0, self.ag_max_x) + self.cooldown = 0 + + def plan(self, ev_total): + """Map scalar exposure target E = exp * ag_x * dg_x to (vblank, exp, ag_code, dg_code).""" + ev = max(self.e_min, min(float(ev_total), self.e_max)) + mid_ag = min(8.0, self.ag_max_x) + if ev <= self.exp_base_max: + exp, ag_x, dg_x, vb = int(round(ev)), 1.0, 1.0, self.vb_min + elif ev <= self.exp_base_max * mid_ag: + exp = self.exp_base_max + ag_x = ev / max(exp, 1) + dg_x, vb = 1.0, self.vb_min + elif ev <= self.exp_lowlight_max * mid_ag: + ag_x = mid_ag + exp = int(round(ev / ag_x)) + dg_x = 1.0 + vb = self.vb_min + max(0, exp - self.exp_base_max) + (16 if exp > self.exp_base_max else 0) + elif ev <= self.exp_lowlight_max * self.ag_max_x: + exp = self.exp_lowlight_max + vb = self.vb_min + max(0, exp - self.exp_base_max) + (16 if exp > self.exp_base_max else 0) + ag_x = ev / max(exp, 1) + dg_x = 1.0 + else: + exp = self.exp_lowlight_max + vb = self.vb_min + max(0, exp - self.exp_base_max) + (16 if exp > self.exp_base_max else 0) + ag_x = self.ag_max_x + dg_x = ev / max(exp * ag_x, 1.0) + + vb = max(self.vb_min, min(vb, self.vb_cap)) + exp = max(self.exp_min, min(exp, self.exp_lowlight_max)) + ag_code = int(round(512.0 * (1.0 - 1.0 / max(ag_x, 1.0)))) + ag_code = max(self.ag_min, min(ag_code, self.ag_max)) + dg_code = int(round(1024.0 * max(dg_x, 1.0))) if self.has_dgain else 1024 + if self.has_dgain: + dg_code = max(min(1024, self.dg_max), min(dg_code, self.dg_max)) + return vb, exp, ag_code, dg_code + + def _apply_exp_vblank(self, vb, exp): + """Enforce sensor ordering: raise VBLANK before raising EXPOSURE; shrink EXPOSURE before shrinking VBLANK.""" + if vb > self.cur_vblank: + self.io.set(V4L2_CID_VBLANK, vb) + self.io.set(V4L2_CID_EXPOSURE, exp) + elif vb < self.cur_vblank: + self.io.set(V4L2_CID_EXPOSURE, exp) + self.io.set(V4L2_CID_VBLANK, vb) + else: + self.io.set(V4L2_CID_EXPOSURE, exp) + + def _apply(self, vb, exp, ag_code, dg_code): + self._apply_exp_vblank(vb, exp) + self.io.set(V4L2_CID_ANALOGUE_GAIN, ag_code) + if self.has_dgain: + self.io.set(V4L2_CID_DIGITAL_GAIN, dg_code) + self.cur_vblank, self.cur_exp, self.cur_ag, self.cur_dg = vb, exp, ag_code, dg_code + + def apply_initial(self): + self.ev_total = float(self.exp_base_max) * min(8.0, self.ag_max_x) + vb, exp, ag, dg = self.plan(self.ev_total) + self._apply(vb, exp, ag, dg) + self.cooldown = 2 + + def update(self, raw_p50, raw_p95): + """Adjust exposure/gain from raw 0..255 luma stats with 2-frame pipeline settling cooldown.""" + if self.cooldown > 0: + self.cooldown -= 1 + return False + if 36.0 <= raw_p50 <= 64.0 and raw_p95 <= 235.0: + return False + if raw_p95 > 240.0: + ratio = max(0.35, 200.0 / max(raw_p95, 1.0)) + else: + ratio = min(4.0, max(0.25, 48.0 / max(raw_p50, 0.5))) + if raw_p95 > 120.0 and raw_p95 * ratio > 235.0: + ratio = max(0.25, min(ratio, 235.0 / raw_p95)) + new_ev = max(self.e_min, min(self.ev_total * (ratio ** 0.75), self.e_max)) + if abs(new_ev - self.ev_total) <= self.ev_total * 0.05: + return False + vb, exp, ag, dg = self.plan(new_ev) + self.ev_total = new_ev + if (vb, exp, ag, dg) != (self.cur_vblank, self.cur_exp, self.cur_ag, self.cur_dg): + self._apply(vb, exp, ag, dg) + self.cooldown = 2 + return True + return False + + def close(self): + if self._closed: + return + self._closed = True + try: + if self.has_dgain: + try: + self.io.set(V4L2_CID_DIGITAL_GAIN, self.init_dg) + except Exception: + pass + try: + self.io.set(V4L2_CID_ANALOGUE_GAIN, self.init_ag) + except Exception: + pass + try: + self._apply_exp_vblank(self.init_vblank, self.init_exp) + except Exception: + pass + finally: + self.io.close() + + def debayer_quad_csi2p( raw_buf, width, @@ -265,51 +486,108 @@ def debayer_quad_csi2p( target_size=(960, 720), high_quality=False, gamma_lut=None, + tone_lut=None, + return_stats=False, cv2_mod=None, np_mod=None, ): - """Debayer 10-bit CSI-2 packed 4x4 Quad-Bayer SRGGB into upright BGR uint8.""" + """Debayer 10-bit CSI-2 packed 4x4 Quad-Bayer SRGGB via 2x2 binning into upright BGR uint8.""" if np_mod is None: import numpy as np_mod if cv2_mod is None: import cv2 as cv2_mod arr = np_mod.frombuffer(raw_buf, dtype=np_mod.uint8, count=height * stride, offset=offset).reshape((height, stride)) - row_bytes = (width // 4) * 5 even_h = (height // 2) * 2 even_w = (width // 4) * 4 + row_bytes = (even_w // 4) * 5 + b5 = arr[:even_h, :row_bytes].reshape((even_h // 2, 2, even_w // 4, 5)) + if high_quality: - p8 = arr[:even_h, :row_bytes].reshape((even_h, even_w // 4, 5))[:, :, :4].reshape((even_h, even_w)) - bayer = ( - ( - p8[0::2, 0::2].astype(np_mod.uint16) - + p8[0::2, 1::2] - + p8[1::2, 0::2] - + p8[1::2, 1::2] - ) - >> 2 - ).astype(np_mod.uint8) + lo = b5[:, :, :, 4] + g0_hi = ( + b5[:, 0, :, 0].astype(np_mod.uint16) + + b5[:, 0, :, 1] + + b5[:, 1, :, 0] + + b5[:, 1, :, 1] + ) << 2 + g0_lo = ( + (lo[:, 0, :] & 3).astype(np_mod.uint16) + + ((lo[:, 0, :] >> 2) & 3) + + (lo[:, 1, :] & 3) + + ((lo[:, 1, :] >> 2) & 3) + ) + g1_hi = ( + b5[:, 0, :, 2].astype(np_mod.uint16) + + b5[:, 0, :, 3] + + b5[:, 1, :, 2] + + b5[:, 1, :, 3] + ) << 2 + g1_lo = ( + ((lo[:, 0, :] >> 4) & 3).astype(np_mod.uint16) + + ((lo[:, 0, :] >> 6) & 3) + + ((lo[:, 1, :] >> 4) & 3) + + ((lo[:, 1, :] >> 6) & 3) + ) + bayer = np_mod.empty((even_h // 2, even_w // 2), dtype=np_mod.uint16) + bayer[:, 0::2] = g0_hi + g0_lo + bayer[:, 1::2] = g1_hi + g1_lo + max_val = 4092.0 + black_cap = 256.0 else: - b5 = arr[:even_h:2, :row_bytes].reshape((even_h // 2, even_w // 4, 5)) - bayer = np_mod.ascontiguousarray(b5[:, :, [0, 2]].reshape((even_h // 2, even_w // 2))) + p8 = b5[:, :, :, :4] + s = p8[:, 0, :, :].astype(np_mod.uint16) + s += p8[:, 1, :, :] + bayer = np_mod.ascontiguousarray((s[:, :, 0::2] + s[:, :, 1::2]).reshape((even_h // 2, even_w // 2))) + max_val = 1020.0 + black_cap = 64.0 - bgr = cv2_mod.cvtColor(bayer, cv2_mod.COLOR_BayerBG2BGR) + bgr16 = cv2_mod.cvtColor(bayer, cv2_mod.COLOR_BayerBG2BGR) if target_size is not None: - bgr = cv2_mod.resize(bgr, target_size, interpolation=cv2_mod.INTER_AREA) + bgr16 = cv2_mod.resize(bgr16, target_size, interpolation=cv2_mod.INTER_AREA) - f = np_mod.maximum(bgr.astype(np_mod.float32) - 16.0, 0.0) - means = f.mean(axis=(0, 1)) + f = bgr16.astype(np_mod.float32) + fh, fw = f.shape[:2] + sub_raw = f[8:-8:4, 8:-8:4] if (fh > 32 and fw > 32) else f + black = float(np_mod.clip(np_mod.percentile(sub_raw, 1), 0.0, black_cap)) + f = np_mod.maximum(f - black, 0.0) * (255.0 / max(max_val - black, 1.0)) + + sub = f[::4, ::4] if (fh >= 32 and fw >= 32) else f + means = sub.mean(axis=(0, 1)) avg = float(means.mean()) - if avg > 1.0: - gains = np_mod.clip(avg / np_mod.maximum(means, 1.0), 0.65, 2.2) - boost = float(np_mod.clip(75.0 / avg, 1.0, 3.8)) - u8 = np_mod.clip(f * (gains * boost), 0, 255).astype(np_mod.uint8) + raw_luma = sub.mean(axis=2) + raw_p50 = float(np_mod.percentile(raw_luma, 50)) + raw_p95 = float(np_mod.percentile(raw_luma, 95)) + + if avg > 0.25: + gains = np_mod.clip(avg / np_mod.maximum(means, max(avg * 0.4, 0.25)), 0.7, 2.0) else: - u8 = np_mod.clip(f, 0, 255).astype(np_mod.uint8) - if gamma_lut is None: - gamma_lut = np_mod.clip((np_mod.linspace(0.0, 1.0, 256) ** (1.0 / 2.2)) * 255.0, 0, 255).astype(np_mod.uint8) - out = cv2_mod.LUT(u8, gamma_lut) - return np_mod.ascontiguousarray(rotate_bgr(out, rot, cv2_mod)) + gains = np_mod.ones(3, dtype=np_mod.float32) + + if raw_p95 < 0.8 and avg < 0.35: + boost = 1.0 + else: + boost = float(np_mod.clip(52.0 / max(raw_p50, avg, 0.25), 1.0, 20.0)) + if raw_p95 * boost > 240.0: + boost = max(1.0, min(boost, 300.0 / max(raw_p95, 1.0))) + + if tone_lut is None: + tone_lut = _get_tone_lut(np_mod) + idx = np_mod.clip((f * (gains * boost) * (4095.0 / 768.0)).astype(np_mod.int32), 0, 4095) + out = tone_lut[idx] + + if boost > 1.8 and out.shape[0] >= 64 and out.shape[1] >= 64: + lab = cv2_mod.cvtColor(out, cv2_mod.COLOR_BGR2LAB) + l_ch, a_ch, b_ch = cv2_mod.split(lab) + l_ch = cv2_mod.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)).apply(l_ch) + a_ch = cv2_mod.GaussianBlur(a_ch, (5, 5), 0) + b_ch = cv2_mod.GaussianBlur(b_ch, (5, 5), 0) + out = cv2_mod.cvtColor(cv2_mod.merge([l_ch, a_ch, b_ch]), cv2_mod.COLOR_LAB2BGR) + + res = np_mod.ascontiguousarray(rotate_bgr(out, rot, cv2_mod)) + if return_stats: + return res, (raw_p50, raw_p95) + return res def bgr_to_cairo_argb32(bgr, np_mod=None): @@ -423,9 +701,10 @@ class CameraEngine: self._alloc = None self._requests = [] self._v4l2 = None + self._ae = None self._started = False self._reuse_arg = None - self._gamma_lut = np.clip((np.linspace(0.0, 1.0, 256) ** (1.0 / 2.2)) * 255.0, 0, 255).astype(np.uint8) + self._tone_lut = _build_tone_lut(np) self._latest_bgr = None self._latest_seq = 0 @@ -529,23 +808,44 @@ class CameraEngine: cam.acquire() self._cam = cam try: + self._sc = None self._raw_sc = None configured = False if role_name == "viewfinder" and info.model.lower() in QUAD_BAYER_MODELS: - try: - cfg = cam.generate_configuration([ - libcamera.StreamRole.Viewfinder, - libcamera.StreamRole.Raw, - ]) - if cfg is not None and len(cfg) >= 2: - cfg.at(0).size = libcamera.Size(640, 480) - cfg.validate() - cam.configure(cfg) - self._sc = cfg.at(0) - self._raw_sc = cfg.at(1) - configured = True - except Exception: - self._raw_sc = None + subdev = find_sensor_subdev(info.model) + if subdev: + ae = None + try: + ae = QuadSensorAE(subdev) + cfg = cam.generate_configuration([libcamera.StreamRole.Raw]) + if cfg is not None and len(cfg) >= 1: + cfg.validate() + cam.configure(cfg) + self._raw_sc = cfg.at(0) + self._sc = None + self._ae = ae + configured = True + except Exception: + if ae is not None: + ae.close() + self._ae = None + self._raw_sc = None + + if not configured: + try: + cfg = cam.generate_configuration([ + libcamera.StreamRole.Viewfinder, + libcamera.StreamRole.Raw, + ]) + if cfg is not None and len(cfg) >= 2: + cfg.at(0).size = libcamera.Size(640, 480) + cfg.validate() + cam.configure(cfg) + self._sc = cfg.at(0) + self._raw_sc = cfg.at(1) + configured = True + except Exception: + self._raw_sc = None if not configured: role = libcamera.StreamRole.StillCapture if role_name == "still" else libcamera.StreamRole.Viewfinder @@ -567,19 +867,26 @@ class CameraEngine: raise RuntimeError("failed to configure %s: %s" % (info.label, chosen_exc)) alloc = libcamera.FrameBufferAllocator(cam) - if alloc.allocate(self._sc.stream) <= 0: - raise RuntimeError("failed to allocate camera buffers for %s" % info.label) self._alloc = alloc reqs = [] - if self._raw_sc is not None: - if alloc.allocate(self._raw_sc.stream) <= 0: - raise RuntimeError("failed to allocate raw buffers for %s" % info.label) + if self._sc is not None and self._raw_sc is not None: + if alloc.allocate(self._sc.stream) <= 0 or alloc.allocate(self._raw_sc.stream) <= 0: + raise RuntimeError("failed to allocate camera buffers for %s" % info.label) for b0, b1 in zip(alloc.buffers(self._sc.stream), alloc.buffers(self._raw_sc.stream)): r = cam.create_request() r.add_buffer(self._sc.stream, b0) r.add_buffer(self._raw_sc.stream, b1) reqs.append(r) + elif self._raw_sc is not None: + if alloc.allocate(self._raw_sc.stream) <= 0: + raise RuntimeError("failed to allocate raw buffers for %s" % info.label) + for b in alloc.buffers(self._raw_sc.stream): + r = cam.create_request() + r.add_buffer(self._raw_sc.stream, b) + reqs.append(r) else: + if alloc.allocate(self._sc.stream) <= 0: + raise RuntimeError("failed to allocate camera buffers for %s" % info.label) for buf in alloc.buffers(self._sc.stream): r = cam.create_request() r.add_buffer(self._sc.stream, buf) @@ -589,6 +896,12 @@ class CameraEngine: self.cm.get_ready_requests() cam.start() self._started = True + if self._ae is not None: + try: + self._ae.apply_initial() + except Exception: + self._ae.close() + self._ae = None for r in self._requests: cam.queue_request(r) except Exception: @@ -596,6 +909,13 @@ class CameraEngine: raise def _close_camera(self): + if self._ae is not None: + try: + self._ae.close() + except Exception: + pass + self._ae = None + if self._v4l2 is not None: try: self._v4l2.release() @@ -630,6 +950,7 @@ class CameraEngine: if not ready: return None frame = None + latest_stats = None for req in ready: if req.status == self.libcamera.Request.Status.Complete: if self._raw_sc is not None and self._raw_sc.stream in req.buffers: @@ -641,7 +962,7 @@ class CameraEngine: fmt = str(self._raw_sc.pixel_format) if "CSI2P" in fmt.upper(): with mmap.mmap(plane.fd, plane.offset + plane.length, mmap.MAP_SHARED, mmap.PROT_READ) as mm: - frame = debayer_quad_csi2p( + frame, latest_stats = debayer_quad_csi2p( mm, w, h, @@ -650,7 +971,8 @@ class CameraEngine: offset=plane.offset, target_size=target_size, high_quality=high_quality, - gamma_lut=self._gamma_lut, + tone_lut=self._tone_lut, + return_stats=True, cv2_mod=self.cv2, np_mod=self.np, ) @@ -674,6 +996,11 @@ class CameraEngine: np_mod=self.np, ) self._requeue(req) + if latest_stats is not None and self._ae is not None: + try: + self._ae.update(*latest_stats) + except Exception: + pass return frame def _run_loop(self): diff --git a/face/chandra-face b/face/chandra-face index ab18f95..7ec355a 100755 --- a/face/chandra-face +++ b/face/chandra-face @@ -101,7 +101,8 @@ class Config: self.timeout = float(get("timeout", "4")) self.threshold = float(get("threshold", "0.42")) self.matches = max(1, int(get("matches", "2"))) - self.dark = float(get("dark", "25")) + self.dark = float(get("dark", "12")) + self.detect_score = float(get("detect_score", "0.65")) self.min_face = int(get("min_face", "80")) self.require_ir = get("require_ir", "no").lower() in ("yes", "true", "1", "on") self.store = get("store", "/var/lib/chandra-face") @@ -278,8 +279,10 @@ class OpenCVRecognizer: if not os.path.exists(p): raise Fail("face models missing: run chandra-face fetch-models", 2) check_trusted(p, "model") - self.det = cv2.FaceDetectorYN.create(det, "", (320, 320), 0.8, 0.3, 5) + self.det = cv2.FaceDetectorYN.create(det, "", (320, 320), cfg.detect_score, 0.3, 5) self.rec = cv2.FaceRecognizerSF.create(rec, "") + self._clahe = cv2.createCLAHE(clipLimit=2.2, tileGridSize=(8, 8)) + self._detect_gamma_lut = np.clip((np.linspace(0.0, 1.0, 256) ** (1.0 / 1.5)) * 255.0, 0, 255).astype(np.uint8) def gray(self, frame): if frame.ndim == 2: @@ -290,12 +293,28 @@ class OpenCVRecognizer: def brightness(self, frame): return float(frame.mean()) + def _enhance_for_detect(self, frame): + """Lift dark frames with mild gamma + LAB CLAHE so YuNet/SFace can read shadow detail.""" + if frame.ndim == 2: + frame = self.cv2.cvtColor(frame, self.cv2.COLOR_GRAY2BGR) + lifted = self.cv2.LUT(frame, self._detect_gamma_lut) + h, w = lifted.shape[:2] + if min(h, w) < 16: + return lifted + lab = self.cv2.cvtColor(lifted, self.cv2.COLOR_BGR2LAB) + l_ch, a_ch, b_ch = self.cv2.split(lab) + l_ch = self._clahe.apply(l_ch) + return self.cv2.cvtColor(self.cv2.merge([l_ch, a_ch, b_ch]), self.cv2.COLOR_LAB2BGR) + def detect(self, frame): if frame.ndim == 2: frame = self.cv2.cvtColor(frame, self.cv2.COLOR_GRAY2BGR) h, w = frame.shape[:2] self.det.setInputSize((w, h)) _, faces = self.det.detect(frame) + if faces is None and float(frame.mean()) < 90.0: + enhanced = self._enhance_for_detect(frame) + _, faces = self.det.detect(enhanced) if faces is None: return [] return [Face(int(f[0]), int(f[1]), int(f[2]), int(f[3]), f) for f in faces] @@ -303,6 +322,8 @@ class OpenCVRecognizer: def embed(self, frame, face): if frame.ndim == 2: frame = self.cv2.cvtColor(frame, self.cv2.COLOR_GRAY2BGR) + if float(frame.mean()) < 55.0: + frame = self._enhance_for_detect(frame) crop = self.rec.alignCrop(frame, face.raw) v = self.rec.feature(crop).flatten() return [float(x) for x in v] @@ -511,6 +532,223 @@ def camera_problem(device): QUAD_BAYER_MODELS = {"imx371"} +VIDIOC_G_CTRL = 0xC008561B +VIDIOC_S_CTRL = 0xC008561C +VIDIOC_QUERYCTRL = 0xC0445624 +V4L2_CID_EXPOSURE = 0x00980911 +V4L2_CID_VBLANK = 0x009E0901 +V4L2_CID_ANALOGUE_GAIN = 0x009E0903 +V4L2_CID_DIGITAL_GAIN = 0x009F0905 + +_QUAD_TONE_LUT = None + + +def _build_tone_lut(np_mod): + """Build 4096-entry uint8 tone LUT: linear 0..160, smooth highlight roll-off to 768, gamma 2.2.""" + x = np_mod.linspace(0.0, 768.0, 4096, dtype=np_mod.float32) + t = np_mod.maximum(x - 160.0, 0.0) / 95.0 + y = np_mod.where(x <= 160.0, x, 160.0 + 95.0 * (t / (1.0 + 0.65 * t))) + y = np_mod.clip(y / 255.0, 0.0, 1.0) + return np_mod.clip((y ** (1.0 / 2.2)) * 255.0, 0, 255).astype(np_mod.uint8) + + +def _get_tone_lut(np_mod): + global _QUAD_TONE_LUT + if _QUAD_TONE_LUT is None: + _QUAD_TONE_LUT = _build_tone_lut(np_mod) + return _QUAD_TONE_LUT + + +def find_sensor_subdev(model): + """Find /dev/v4l-subdevN matching sensor `model`, or None.""" + if not model: + return None + want = model.lower() + for p in sorted(glob.glob("/sys/class/video4linux/v4l-subdev*/name")): + try: + with open(p) as fh: + name = fh.read().strip().lower() + except OSError: + continue + if name == want or name.startswith(want + " "): + return "/dev/" + os.path.basename(os.path.dirname(p)) + return None + + +class _V4L2SubdevIO: + """Thin ioctl wrapper over a V4L2 subdevice file descriptor.""" + + def __init__(self, path): + self.fd = os.open(path, os.O_RDWR) + + def query(self, cid): + buf = bytearray(68) + struct.pack_into("= 0: + try: + os.close(self.fd) + finally: + self.fd = -1 + + +class QuadSensorAE: + """Direct V4L2 subdev auto-exposure and gain controller for Raw-only Quad-Bayer capture.""" + + def __init__(self, subdev_path, io=None): + self.io = io if io is not None else _V4L2SubdevIO(subdev_path) + self._closed = False + try: + self.vb_min, self.vb_max, _, _ = self.io.query(V4L2_CID_VBLANK) + self.exp_min, self.exp_max_now, _, _ = self.io.query(V4L2_CID_EXPOSURE) + self.ag_min, self.ag_max, _, _ = self.io.query(V4L2_CID_ANALOGUE_GAIN) + self.init_vblank = self.io.get(V4L2_CID_VBLANK) + self.init_exp = self.io.get(V4L2_CID_EXPOSURE) + self.init_ag = self.io.get(V4L2_CID_ANALOGUE_GAIN) + try: + self.dg_min, self.dg_max, _, _ = self.io.query(V4L2_CID_DIGITAL_GAIN) + self.init_dg = self.io.get(V4L2_CID_DIGITAL_GAIN) + self.has_dgain = True + except OSError: + self.dg_min, self.dg_max, self.init_dg, self.has_dgain = 1024, 1024, 1024, False + except Exception: + self.io.close() + raise + + self.exp_base_max = max(self.exp_min + 1, self.exp_max_now - max(0, self.init_vblank - self.vb_min)) + self.vb_cap = min(self.vb_max, 9500) + self.exp_lowlight_max = min(self.exp_base_max + max(0, self.vb_cap - self.vb_min), 12000) + self.ag_max_x = 512.0 / max(512 - min(self.ag_max, 504), 1) + self.dg_max_x = min(self.dg_max / 1024.0, 4.0) if self.has_dgain else 1.0 + self.e_min = float(max(20, self.exp_min)) + self.e_max = float(self.exp_lowlight_max) * self.ag_max_x * self.dg_max_x + self.cur_vblank = self.init_vblank + self.cur_exp = self.init_exp + self.cur_ag = self.init_ag + self.cur_dg = self.init_dg + self.ev_total = float(self.exp_base_max) * min(8.0, self.ag_max_x) + self.cooldown = 0 + + def plan(self, ev_total): + """Map scalar exposure target E = exp * ag_x * dg_x to (vblank, exp, ag_code, dg_code).""" + ev = max(self.e_min, min(float(ev_total), self.e_max)) + mid_ag = min(8.0, self.ag_max_x) + if ev <= self.exp_base_max: + exp, ag_x, dg_x, vb = int(round(ev)), 1.0, 1.0, self.vb_min + elif ev <= self.exp_base_max * mid_ag: + exp = self.exp_base_max + ag_x = ev / max(exp, 1) + dg_x, vb = 1.0, self.vb_min + elif ev <= self.exp_lowlight_max * mid_ag: + ag_x = mid_ag + exp = int(round(ev / ag_x)) + dg_x = 1.0 + vb = self.vb_min + max(0, exp - self.exp_base_max) + (16 if exp > self.exp_base_max else 0) + elif ev <= self.exp_lowlight_max * self.ag_max_x: + exp = self.exp_lowlight_max + vb = self.vb_min + max(0, exp - self.exp_base_max) + (16 if exp > self.exp_base_max else 0) + ag_x = ev / max(exp, 1) + dg_x = 1.0 + else: + exp = self.exp_lowlight_max + vb = self.vb_min + max(0, exp - self.exp_base_max) + (16 if exp > self.exp_base_max else 0) + ag_x = self.ag_max_x + dg_x = ev / max(exp * ag_x, 1.0) + + vb = max(self.vb_min, min(vb, self.vb_cap)) + exp = max(self.exp_min, min(exp, self.exp_lowlight_max)) + ag_code = int(round(512.0 * (1.0 - 1.0 / max(ag_x, 1.0)))) + ag_code = max(self.ag_min, min(ag_code, self.ag_max)) + dg_code = int(round(1024.0 * max(dg_x, 1.0))) if self.has_dgain else 1024 + if self.has_dgain: + dg_code = max(min(1024, self.dg_max), min(dg_code, self.dg_max)) + return vb, exp, ag_code, dg_code + + def _apply_exp_vblank(self, vb, exp): + """Enforce sensor ordering: raise VBLANK before raising EXPOSURE; shrink EXPOSURE before shrinking VBLANK.""" + if vb > self.cur_vblank: + self.io.set(V4L2_CID_VBLANK, vb) + self.io.set(V4L2_CID_EXPOSURE, exp) + elif vb < self.cur_vblank: + self.io.set(V4L2_CID_EXPOSURE, exp) + self.io.set(V4L2_CID_VBLANK, vb) + else: + self.io.set(V4L2_CID_EXPOSURE, exp) + + def _apply(self, vb, exp, ag_code, dg_code): + self._apply_exp_vblank(vb, exp) + self.io.set(V4L2_CID_ANALOGUE_GAIN, ag_code) + if self.has_dgain: + self.io.set(V4L2_CID_DIGITAL_GAIN, dg_code) + self.cur_vblank, self.cur_exp, self.cur_ag, self.cur_dg = vb, exp, ag_code, dg_code + + def apply_initial(self): + self.ev_total = float(self.exp_base_max) * min(8.0, self.ag_max_x) + vb, exp, ag, dg = self.plan(self.ev_total) + self._apply(vb, exp, ag, dg) + self.cooldown = 2 + + def update(self, raw_p50, raw_p95): + """Adjust exposure/gain from raw 0..255 luma stats with 2-frame pipeline settling cooldown.""" + if self.cooldown > 0: + self.cooldown -= 1 + return False + if 36.0 <= raw_p50 <= 64.0 and raw_p95 <= 235.0: + return False + if raw_p95 > 240.0: + ratio = max(0.35, 200.0 / max(raw_p95, 1.0)) + else: + ratio = min(4.0, max(0.25, 48.0 / max(raw_p50, 0.5))) + if raw_p95 > 120.0 and raw_p95 * ratio > 235.0: + ratio = max(0.25, min(ratio, 235.0 / raw_p95)) + new_ev = max(self.e_min, min(self.ev_total * (ratio ** 0.75), self.e_max)) + if abs(new_ev - self.ev_total) <= self.ev_total * 0.05: + return False + vb, exp, ag, dg = self.plan(new_ev) + self.ev_total = new_ev + if (vb, exp, ag, dg) != (self.cur_vblank, self.cur_exp, self.cur_ag, self.cur_dg): + self._apply(vb, exp, ag, dg) + self.cooldown = 2 + return True + return False + + def close(self): + if self._closed: + return + self._closed = True + try: + if self.has_dgain: + try: + self.io.set(V4L2_CID_DIGITAL_GAIN, self.init_dg) + except Exception: + pass + try: + self.io.set(V4L2_CID_ANALOGUE_GAIN, self.init_ag) + except Exception: + pass + try: + self._apply_exp_vblank(self.init_vblank, self.init_exp) + except Exception: + pass + finally: + self.io.close() + def rotate_bgr(bgr, rot, cv2_mod): """Rotate BGR frame according to libcamera.properties.Rotation (CCW mounting angle).""" @@ -533,37 +771,72 @@ def debayer_quad_csi2p( offset=0, target_size=(640, 480), gamma_lut=None, + tone_lut=None, + return_stats=False, cv2_mod=None, np_mod=None, ): - """Debayer 10-bit CSI-2 packed 4x4 Quad-Bayer SRGGB into upright BGR uint8.""" + """Debayer 10-bit CSI-2 packed 4x4 Quad-Bayer SRGGB via 2x2 binning into upright BGR uint8.""" if np_mod is None: import numpy as np_mod if cv2_mod is None: import cv2 as cv2_mod arr = np_mod.frombuffer(raw_buf, dtype=np_mod.uint8, count=height * stride, offset=offset).reshape((height, stride)) - row_bytes = (width // 4) * 5 even_h = (height // 2) * 2 - b5 = arr[:even_h:2, :row_bytes].reshape((even_h // 2, width // 4, 5)) - bayer = np_mod.ascontiguousarray(b5[:, :, [0, 2]].reshape((even_h // 2, width // 2))) - bgr = cv2_mod.cvtColor(bayer, cv2_mod.COLOR_BayerBG2BGR) - if target_size is not None: - bgr = cv2_mod.resize(bgr, target_size, interpolation=cv2_mod.INTER_AREA) + even_w = (width // 4) * 4 + row_bytes = (even_w // 4) * 5 + p8 = arr[:even_h, :row_bytes].reshape((even_h // 2, 2, even_w // 4, 5))[:, :, :, :4] + s = p8[:, 0, :, :].astype(np_mod.uint16) + s += p8[:, 1, :, :] + bayer10 = np_mod.ascontiguousarray((s[:, :, 0::2] + s[:, :, 1::2]).reshape((even_h // 2, even_w // 2))) - f = np_mod.maximum(bgr.astype(np_mod.float32) - 16.0, 0.0) - means = f.mean(axis=(0, 1)) + bgr16 = cv2_mod.cvtColor(bayer10, cv2_mod.COLOR_BayerBG2BGR) + if target_size is not None: + bgr16 = cv2_mod.resize(bgr16, target_size, interpolation=cv2_mod.INTER_AREA) + + f = bgr16.astype(np_mod.float32) + fh, fw = f.shape[:2] + sub_raw = f[8:-8:4, 8:-8:4] if (fh > 32 and fw > 32) else f + black = float(np_mod.clip(np_mod.percentile(sub_raw, 1), 0.0, 64.0)) + f = np_mod.maximum(f - black, 0.0) * (255.0 / max(1020.0 - black, 1.0)) + + sub = f[::4, ::4] if (fh >= 32 and fw >= 32) else f + means = sub.mean(axis=(0, 1)) avg = float(means.mean()) - if avg > 1.0: - gains = np_mod.clip(avg / np_mod.maximum(means, 1.0), 0.65, 2.2) - boost = float(np_mod.clip(75.0 / avg, 1.0, 3.8)) - u8 = np_mod.clip(f * (gains * boost), 0, 255).astype(np_mod.uint8) + raw_luma = sub.mean(axis=2) + raw_p50 = float(np_mod.percentile(raw_luma, 50)) + raw_p95 = float(np_mod.percentile(raw_luma, 95)) + + if avg > 0.25: + gains = np_mod.clip(avg / np_mod.maximum(means, max(avg * 0.4, 0.25)), 0.7, 2.0) else: - u8 = np_mod.clip(f, 0, 255).astype(np_mod.uint8) - if gamma_lut is None: - gamma_lut = np_mod.clip((np_mod.linspace(0.0, 1.0, 256) ** (1.0 / 2.2)) * 255.0, 0, 255).astype(np_mod.uint8) - out = cv2_mod.LUT(u8, gamma_lut) - return np_mod.ascontiguousarray(rotate_bgr(out, rot, cv2_mod)) + gains = np_mod.ones(3, dtype=np_mod.float32) + + if raw_p95 < 0.8 and avg < 0.35: + boost = 1.0 + else: + boost = float(np_mod.clip(52.0 / max(raw_p50, avg, 0.25), 1.0, 20.0)) + if raw_p95 * boost > 240.0: + boost = max(1.0, min(boost, 300.0 / max(raw_p95, 1.0))) + + if tone_lut is None: + tone_lut = _get_tone_lut(np_mod) + idx = np_mod.clip((f * (gains * boost) * (4095.0 / 768.0)).astype(np_mod.int32), 0, 4095) + out = tone_lut[idx] + + if boost > 1.8 and out.shape[0] >= 64 and out.shape[1] >= 64: + lab = cv2_mod.cvtColor(out, cv2_mod.COLOR_BGR2LAB) + l_ch, a_ch, b_ch = cv2_mod.split(lab) + l_ch = cv2_mod.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)).apply(l_ch) + a_ch = cv2_mod.GaussianBlur(a_ch, (5, 5), 0) + b_ch = cv2_mod.GaussianBlur(b_ch, (5, 5), 0) + out = cv2_mod.cvtColor(cv2_mod.merge([l_ch, a_ch, b_ch]), cv2_mod.COLOR_LAB2BGR) + + res = np_mod.ascontiguousarray(rotate_bgr(out, rot, cv2_mod)) + if return_stats: + return res, (raw_p50, raw_p95) + return res class LibcameraCamera: @@ -581,12 +854,13 @@ class LibcameraCamera: self.cv2, self.libcamera, self.mmap, self.np = cv2, libcamera, mmap, np reuse_enum = getattr(libcamera.Request, "Reuse", None) or getattr(libcamera.Request, "ReuseFlag", None) self._reuse_arg = getattr(reuse_enum, "ReuseBuffers", None) if reuse_enum is not None else None - self._gamma_lut = np.clip((np.linspace(0.0, 1.0, 256) ** (1.0 / 2.2)) * 255.0, 0, 255).astype(np.uint8) + self._tone_lut = _build_tone_lut(np) self.sc = None self.raw_sc = None self.alloc = None self.requests = [] self._started = False + self._ae = None cid = device[len("libcamera:"):] self.cm = libcamera.CameraManager.singleton() @@ -601,21 +875,40 @@ class LibcameraCamera: raise Fail("couldn't acquire camera %s: %s" % (device, e), 2) try: if self.model in QUAD_BAYER_MODELS: - try: - cfg = self.cam.generate_configuration([ - libcamera.StreamRole.Viewfinder, - libcamera.StreamRole.Raw, - ]) - if cfg is not None and len(cfg) >= 2: - cfg.at(0).size = libcamera.Size(640, 480) - cfg.validate() - self.cam.configure(cfg) - self.sc = cfg.at(0) - self.raw_sc = cfg.at(1) - except Exception: - self.raw_sc = None + subdev = find_sensor_subdev(self.model) + if subdev: + ae = None + try: + ae = QuadSensorAE(subdev) + cfg = self.cam.generate_configuration([libcamera.StreamRole.Raw]) + if cfg is not None and len(cfg) >= 1: + cfg.validate() + self.cam.configure(cfg) + self.raw_sc = cfg.at(0) + self.sc = None + self._ae = ae + except Exception: + if ae is not None: + ae.close() + self._ae = None + self.raw_sc = None - if self.raw_sc is None: + if self.raw_sc is None: + try: + cfg = self.cam.generate_configuration([ + libcamera.StreamRole.Viewfinder, + libcamera.StreamRole.Raw, + ]) + if cfg is not None and len(cfg) >= 2: + cfg.at(0).size = libcamera.Size(640, 480) + cfg.validate() + self.cam.configure(cfg) + self.sc = cfg.at(0) + self.raw_sc = cfg.at(1) + except Exception: + self.raw_sc = None + + if self.sc is None and self.raw_sc is None: cfg = self.cam.generate_configuration([libcamera.StreamRole.Viewfinder]) self.sc = cfg.at(0) self.sc.size = libcamera.Size(640, 480) @@ -623,18 +916,25 @@ class LibcameraCamera: self.cam.configure(cfg) self.alloc = libcamera.FrameBufferAllocator(self.cam) - if self.alloc.allocate(self.sc.stream) <= 0: - raise Fail("couldn't allocate camera buffers for %s" % device, 2) self.requests = [] - if self.raw_sc is not None: - if self.alloc.allocate(self.raw_sc.stream) <= 0: - raise Fail("couldn't allocate raw buffers for %s" % device, 2) + if self.sc is not None and self.raw_sc is not None: + if self.alloc.allocate(self.sc.stream) <= 0 or self.alloc.allocate(self.raw_sc.stream) <= 0: + raise Fail("couldn't allocate camera buffers for %s" % device, 2) for b0, b1 in zip(self.alloc.buffers(self.sc.stream), self.alloc.buffers(self.raw_sc.stream)): r = self.cam.create_request() r.add_buffer(self.sc.stream, b0) r.add_buffer(self.raw_sc.stream, b1) self.requests.append(r) + elif self.raw_sc is not None: + if self.alloc.allocate(self.raw_sc.stream) <= 0: + raise Fail("couldn't allocate raw buffers for %s" % device, 2) + for b in self.alloc.buffers(self.raw_sc.stream): + r = self.cam.create_request() + r.add_buffer(self.raw_sc.stream, b) + self.requests.append(r) else: + if self.alloc.allocate(self.sc.stream) <= 0: + raise Fail("couldn't allocate camera buffers for %s" % device, 2) for buf in self.alloc.buffers(self.sc.stream): r = self.cam.create_request() r.add_buffer(self.sc.stream, buf) @@ -642,6 +942,12 @@ class LibcameraCamera: self.cm.get_ready_requests() self.cam.start() self._started = True + if self._ae is not None: + try: + self._ae.apply_initial() + except Exception: + self._ae.close() + self._ae = None for r in self.requests: self.cam.queue_request(r) except Exception as e: @@ -675,7 +981,7 @@ class LibcameraCamera: if "CSI2P" not in fmt.upper(): raise Fail("unsupported quad raw format %s" % fmt, 2) with self.mmap.mmap(p.fd, p.offset + p.length, self.mmap.MAP_SHARED, self.mmap.PROT_READ) as mm: - return debayer_quad_csi2p( + frame, (raw_p50, raw_p95) = debayer_quad_csi2p( mm, w, h, @@ -683,10 +989,17 @@ class LibcameraCamera: rot=self.rot, offset=p.offset, target_size=(640, 480), - gamma_lut=self._gamma_lut, + tone_lut=self._tone_lut, + return_stats=True, cv2_mod=self.cv2, np_mod=self.np, ) + if self._ae is not None: + try: + self._ae.update(raw_p50, raw_p95) + except Exception: + pass + return frame def _requeue(self, req): if self._reuse_arg is not None: @@ -724,6 +1037,12 @@ class LibcameraCamera: return None def close(self): + if getattr(self, "_ae", None) is not None: + try: + self._ae.close() + except Exception: + pass + self._ae = None try: if getattr(self, "_started", False): self.cam.stop() diff --git a/face/face.conf b/face/face.conf index a9ca65b..1934092 100644 --- a/face/face.conf +++ b/face/face.conf @@ -16,7 +16,7 @@ threshold = 0.42 # How many frames must match. matches = 2 # Frames darker than this (0-255 average) are skipped: IR emitters take a moment to light up. -dark = 25 +dark = 12 # Smallest face to use, in pixels (a face far away is too blurry to trust). min_face = 80 # yes: only accept grey (infrared) frames, refusing a colour webcam.