Files
windows-fenjian/core/evidence/frames.py
T

1306 lines
55 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""帧源:UVC 摄像头(子进程取帧)+ "确认后新帧"证据链(铁律 6)。
为什么用子进程:cv2.VideoCapture 在部分 Windows 驱动上会无限期阻塞,
放在主进程里会让整个界面假死。子进程取帧后通过管道送 JPEG,父进程只解码,
6 秒没有新消息就杀掉重开,界面永远有响应。
证据链 capture_confirmed() 必须满足:
① 请求后至少 2 个新帧 ② 到达时刻 > 请求时刻
③ 帧龄 <= 700ms ④ SHA256 指纹
不合格重试(最多 16 次 × 150ms),不合格绝不顶替留档。
simulate 模式生成合成画面(含单调递增序号),可完整走证据链。
"""
import os
import sys
import time
import json
import queue
import struct
import hashlib
import datetime
import threading
import subprocess
import cv2
import numpy as np
from core.evidence import usbcam
CACHE_PATH = os.path.join('data', 'camera_auto.json')
CONFIRMED_MIN_NEW_FRAMES = 2
MAX_CAPTURE_FRAME_AGE_MS = 700
ARCHIVE_MAX_ATTEMPTS = 16
CHILD_STALL_SEC = 6.0
FIRST_MSG_SEC = 24.0 # 首条消息要等设备打开 + 逐档试分辨率(8MP 模组较慢)
RETRY_WINDOW_SEC = 30.0 # 全部设备都试过一轮后,等这么久再重来(支持拔插恢复)
BAD_TTL_SEC = 180.0 # 打不开的设备冷却时间(期间不再死等它)
SETTLE_SEC = 0.45 # 释放设备后等驱动真正放手的缓冲(否则探测必「被占用」)
# 帧解码节流:相机出 30fps,父进程只解最新一帧。预览 90ms 刷新一次、
# 识别只要一帧静图,多解的全是白烧 CPU(1080p JPEG 一帧 ≈16ms,现场弱机更慢)。
_DECODE_GAP = 0.075 # 正常 ≈13fps(强机默认)
_DECODE_GAP_LOW = 0.30 # 拖动名单时 ≈3fps
_DECODE_GAP_WEAK = 0.17 # 弱机(2 逻辑核及以下)≈6fps
def default_decode_gap(cam_cfg=None):
"""这台机器该多久解一帧。
v1.0.52:现场是 i5-4200U(2 核 4 线程、1.6GHz、15W),720p JPEG 解一帧
8~12ms,13fps 就要吃掉半核 —— 而预览本来只要每秒 8 帧、识别只要一张
静帧。所以:配置里写了 camera.decode_fps 就听配置的;没写就按核数
自动分档(≤2 逻辑核 → 6fps)。
"""
try:
fps = float((cam_cfg or {}).get('decode_fps') or 0)
except (AttributeError, TypeError, ValueError):
fps = 0.0
if fps > 0:
return 1.0 / max(2.0, min(20.0, fps))
if (os.cpu_count() or 4) <= 2:
return _DECODE_GAP_WEAK
return _DECODE_GAP
BACKEND_ORDER = ('dshow', 'msmf')
DEFAULT_SIZE_CHAIN = ((3264, 2448), (2592, 1944), (2560, 1440),
(1920, 1080), (1280, 720))
if getattr(sys, 'frozen', False):
# 打包后:项目根 = exe 所在目录(.py 都在 _MEIPASS 里,不能拿来当根)
_ROOT = os.path.dirname(os.path.abspath(sys.executable))
else:
_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(
os.path.abspath(__file__))))
def snapshot_dir(cfg=None):
"""抓拍存到哪:storage.snapshot_dir > capture_dir > data/snapshots。
绝对路径直接用(现场 C 盘小,抓拍落 D 盘);相对路径相对**程序目录**,
不是当前工作目录 —— 快捷方式启动时 cwd 可能是别处。
"""
raw = ''
if isinstance(cfg, dict):
st = cfg.get('storage')
if isinstance(st, dict):
raw = str(st.get('snapshot_dir') or '').strip()
if not raw:
raw = str(cfg.get('capture_dir') or '').strip()
raw = raw or os.path.join('data', 'snapshots')
raw = os.path.expandvars(os.path.expanduser(raw))
if not os.path.isabs(raw):
raw = os.path.join(_ROOT, raw)
return os.path.normpath(raw)
def _dir_writable(d):
try:
os.makedirs(d, exist_ok=True)
probe = os.path.join(d, '.wb_probe')
with open(probe, 'wb') as f:
f.write(b'ok')
os.remove(probe)
return True
except OSError:
return False
def _child_cmd(module, *args):
"""子进程命令行:开发时用 python -m,打包后用 exe 自己分发。
打包后 sys.executable 是本 exe,不认 -m 参数,必须走 --wb-child 分发
(见 main.py 里的 _run_child)。
"""
if getattr(sys, 'frozen', False):
return [sys.executable, '--wb-child', module] + [str(a) for a in args]
return [sys.executable, '-m', module] + [str(a) for a in args]
# ---------------------------------------------------------------- 设备探测
def discover_devices(conf_idx=0, want_w=1280, want_h=720, timeout=25.0,
indices=None, diag=None):
"""子进程探测可用摄像头(硬超时,避免 cv2 阻塞卡死主程序)
indices 为 None 时探测 conf_idx + 0~4;否则只探给定的索引
(USB 模式下只探 USB 摄像头,省时间也不去碰虚拟设备)。
diag 传入 dict 时,失败设备的原因会写进去:{索引: 'open'|'noframe'}
—— 给现场区分「被占用」和「模组卡死」,两者处置完全不同。
"""
if indices is None:
indices = [int(conf_idx)] + [i for i in range(5)
if i != int(conf_idx)]
indices = [int(i) for i in sorted(set(indices))]
if not indices:
return []
cmd = _child_cmd('core.evidence._probe_child',
','.join(str(i) for i in indices),
int(want_w), int(want_h))
found = []
try:
env = dict(os.environ)
env['PYTHONPATH'] = _ROOT + os.pathsep + env.get('PYTHONPATH', '')
p = subprocess.Popen(cmd, cwd=_ROOT, env=env,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True, bufsize=1)
except Exception:
return found
q = queue.Queue()
def _reader():
try:
for line in p.stdout:
q.put(line)
except Exception:
pass
q.put(None)
threading.Thread(target=_reader, daemon=True).start()
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
line = q.get(timeout=0.3)
except queue.Empty:
if p.poll() is not None:
break
continue
if line is None:
break
s = line.strip()
if s == 'END':
break
if s.startswith('{'):
try:
obj = json.loads(s)
except ValueError:
continue
if obj.get('fail'):
if diag is not None:
try:
diag[int(obj.get('index', -1))] = obj['fail']
except Exception: # noqa: BLE001
pass
continue
found.append(obj)
try:
p.kill()
except Exception:
pass
return found
def diag_hint(diag, indices=None):
"""把探测失败原因翻成现场能照着做的话(没信息就返回空串)
实测(Windows + UVC 驱动):摄像头被别人占着时 VideoCapture 往往
「打开成功、一帧也读不到」,不是打不开。所以 noframe 基本等于被占用,
真正的设备故障(拔插才好)是少数。
"""
if not diag:
return ''
keys = list(indices) if indices is not None else list(diag.keys())
busy = sorted({int(i) for i in keys if diag.get(int(i)) == 'open'})
dead = sorted({int(i) for i in keys if diag.get(int(i)) == 'noframe'})
tips = []
if busy:
tips.append('%s 号打不开:没插好、驱动异常,或被系统/安全软件禁用'
% '、'.join(str(i) for i in busy))
if dead:
tips.append('%s 号能打开却拿不到画面:多半是别的程序占着'
'(微信/相机/浏览器/会议软件),也可能模组或驱动卡住'
'→ 先关掉占用它的程序;仍不行拔插一次摄像头 USB'
% '、'.join(str(i) for i in dead))
return ';'.join(tips)
_ORPHAN_TTL = 30.0
_ORPHAN_CACHE = {'at': -999.0, 'orphan': [], 'other': []}
def _pid_alive(pid):
"""WAIT_TIMEOUT(0x102) = 进程还在;打不开句柄 = 已退出"""
if not pid:
return False
try:
import ctypes
k32 = ctypes.windll.kernel32
h = k32.OpenProcess(0x00100000, False, int(pid)) # SYNCHRONIZE
if not h:
return False
try:
return k32.WaitForSingleObject(h, 0) == 0x102
finally:
k32.CloseHandle(h)
except Exception:
return True # 判不出来就当活着,宁可少报也别误报
def child_report():
"""查本程序的取帧子进程:谁成了孤儿、谁属于另一个实例。
返回 {'orphan': [子进程PID], 'other': [另一个主程序PID]}
「明明没开别的软件却说被占用」几乎都出在这两处:
· orphan —— 上次程序被任务管理器强杀,子进程还活着,一直握着摄像头;
· other —— 这台机器开了两个本程序,摄像头被另一个实例的取帧进程占着。
查一次约 0.6~1 秒,结果缓存 30 秒(只在报错路径调用)。
"""
now = time.monotonic()
if now - _ORPHAN_CACHE['at'] < _ORPHAN_TTL:
return {'orphan': list(_ORPHAN_CACHE['orphan']),
'other': list(_ORPHAN_CACHE['other'])}
orphan, other = [], []
if os.name == 'nt':
try:
# 模式串在 PowerShell 里拼出来:命令行若出现完整的 --wb-child 字面量,
# powershell.exe 自己也会被 Where-Object 匹配到(它的命令行就在里面)
ps = ('$pat = "--wb" + "-child"; '
'Get-CimInstance Win32_Process | Where-Object { '
'$_.Name -notlike "powershell*" -and $_.Name -notlike "pwsh*" '
'-and $_.CommandLine -like "*$pat*" } | '
'ForEach-Object { "$($_.ProcessId) $($_.ParentProcessId)" }')
r = subprocess.run(
['powershell', '-NoProfile', '-NonInteractive',
'-Command', ps],
capture_output=True, text=True, timeout=8,
creationflags=0x08000000) # 不弹黑框
for ln in (r.stdout or '').splitlines():
part = ln.split()
if len(part) != 2 or not part[0].isdigit():
continue
pid, ppid = int(part[0]), int(part[1])
if pid == os.getpid():
continue
if _pid_alive(ppid):
if ppid != os.getpid() and ppid not in other:
other.append(ppid) # 另一个实例的子进程
else:
orphan.append(pid) # 父进程没了 = 孤儿
except Exception:
pass
_ORPHAN_CACHE.update(at=now, orphan=orphan, other=other)
return {'orphan': orphan, 'other': other}
def orphan_children():
"""残留的取帧/探测子进程 PID(父进程已退出,却还握着摄像头)"""
return list(child_report()['orphan'])
def holder_hint():
"""「本程序自己占着摄像头」的提示;没有就返回空串"""
r = child_report()
tips = []
if r['other']:
tips.append('本程序还开着另一个窗口(PID %s),摄像头被它占着,'
'先关掉一个' % ','.join(str(p) for p in r['other'][:3]))
if r['orphan']:
tips.append('有 %d 个残留取帧进程(PID %s),先在任务管理器结束它'
% (len(r['orphan']),
','.join(str(p) for p in r['orphan'][:5])))
return ';'.join(tips)
def list_cameras_full(max_index=4, width=1280, height=720):
"""扫描摄像头并区分 USB / 非 USB(设置页“扫描”用)。
返回 {'usb': [...], 'ignored': [...], 'mode': 'usb'|'guess'|'unknown',
'note': str, 'error': str}
usb 元素:{'index','backend','width','height','name','vid','pid'}
ignored 元素:{'index','name','reason'}
"""
# 调用方(设置页扫描)刚 suspend 释放设备,驱动真正放手有 0.3~1 秒延迟;
# 不等这一下,探测必然拿不到设备,又被误判成「被其它程序占用」
time.sleep(SETTLE_SEC)
info = usbcam.enumerate_cameras(force=True)
out = {'usb': [], 'ignored': list(info['ignored']), 'mode': info['mode'],
'note': info['note'], 'error': ''}
if info['mode'] == 'unknown':
# 取不到设备名就无法按索引判定 USB,不再乱开设备
out['error'] = ('无法读取摄像头设备列表(%s)。'
'请确认已安装 pygrabber(pip install pygrabber)。'
% (info.get('names_err') or '未知原因'))
return out
cand = [d['index'] for d in info['usb']]
if not cand:
out['error'] = ('未发现 USB 摄像头。请确认:摄像头插在主机 USB 口'
'(不要插扩展坞/HUB)、设备管理器"照相机"下可见;'
'虚拟摄像头/手机投屏/IP 摄像头不在允许范围内。')
return out
# 每台设备 DSHOW 打不开可能耗 40 秒,超时要按设备数量放大,否则后面的被截断
diag = {}
found = discover_devices(cand[0], width, height,
timeout=20.0 + 16.0 * len(cand), indices=cand,
diag=diag)
by_idx = {int(d['index']): d for d in found}
dead = []
for d in info['usb']:
hit = by_idx.get(d['index'])
if not hit:
dead.append(d) # 打不开:原因记在 diag,下面统一翻译
continue
out['usb'].append({'index': d['index'], 'backend': hit['backend'],
'width': hit['width'], 'height': hit['height'],
'name': d['name'], 'vid': d.get('vid', ''),
'pid': d.get('pid', '')})
if dead:
idxs = [d['index'] for d in dead]
out['note'] += '|没画面的 USB 摄像头:%s' % (
diag_hint(diag, idxs)
or '、'.join('%d 号 %s' % (d['index'], d['name']) for d in dead))
if not out['usb']:
parts = [diag_hint(diag, cand)
or ('检测到 %d 台 USB 摄像头,但都没画面(探测超时或驱动无响应)'
% len(cand))]
own = holder_hint()
if own:
parts.append(own)
out['error'] = ';'.join(p for p in parts if p)
return out
def list_cameras(max_index=4, width=1280, height=720):
"""只返回可用 USB 摄像头(选择后热切换用)"""
return list_cameras_full(max_index, width, height).get('usb', [])
_JOB = None
def _job():
"""Windows 作业对象:父进程退出时自动杀掉取帧子进程(防孤儿占设备)"""
global _JOB
if _JOB is not None:
return _JOB
try:
import win32job
job = win32job.CreateJobObject(None, 'inbound-sorting-cam')
info = win32job.QueryInformationJobObject(
job, win32job.JobObjectExtendedLimitInformation)
info['BasicLimitInformation']['LimitFlags'] |= \
win32job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
win32job.SetInformationJobObject(
job, win32job.JobObjectExtendedLimitInformation, info)
_JOB = job
except Exception:
_JOB = False
return _JOB
def _assign_to_job(proc):
job = _job()
if not job:
return
try:
import win32job
import win32api
h = win32api.OpenProcess(0x1F0FFF, False, proc.pid)
win32job.AssignProcessToJobObject(job, h)
except Exception:
pass
class FrameSource:
def __init__(self, cfg):
self.cfg = cfg.get('camera', {})
self.latest = None # (frame_seq, arrived_mono, bgr)
self.error = None
self.status = ''
self.opened = None # (index, backend, w, h, name)
self._seq = 0
self._lock = threading.Lock()
# 帧解码最小间隔(节流用,见 set_low_power)。弱机自动降档,
# 也可在 config 里写 camera.decode_fps 指定。
self._base_gap = default_decode_gap(self.cfg)
self._decode_gap = self._base_gap
# v1.0.52:实测解码耗时(EMA)。不猜 CPU 型号,直接量:
# 同一份 JPEG 在这台机器上解一帧要多久,就知道该多久解一帧。
self.decode_ms = 0.0
self.weak = False # 弱机标记,界面据此少画几帧预览
self.perf_note = '' # 给界面写日志用的一句话(只报一次)
self._frames_seen = 0
self._tuned = False
self._perf_fixed = bool((self.cfg or {}).get('decode_fps'))
self._running = False
self._preview_paused = False
self._reload = False # 热切换请求(reconfigure 置位)
self._suspended = False # 扫描设备时临时停帧(释放设备)
self._refused = False # 已拒绝的设备(非 USB),丢弃其画面
self._bad = {} # 名称 → 失败时刻(避免每次启动都死等坏设备)
self.diag = {} # 最近一次探测的失败原因 {索引: open/noframe}
self.auto_size = None # 分辨率被自动降档时记一笔,由界面写回配置
self.focus_info = None # 子进程回报的对焦值(设置页诊断用)
self.last_focus_wait = None # 最近一次"等对焦"的结果(诊断用)
self._proc = None
# 数字变焦:预览和抓拍用同一份裁剪,1.0=全幅,越大越近
try:
self.zoom = max(1.0, min(4.0, float(self.cfg.get('zoom') or 1.0)))
except (TypeError, ValueError):
self.zoom = 1.0
self._focus_locked = False # 相机被锁死在固定焦距(此时不必再戳对焦)
self._memo_at = 0.0 # 上次写焦距记忆的时刻(节流)
# 抓拍存放目录:可指到 D 盘。第一次真正写盘时才验证可用性,
# 不可写就回退程序目录下的 data/snapshots(并留一句说明给界面)。
self.snap_dir = snapshot_dir(cfg)
self.snap_note = ''
self._snap_ready = False
# ------------------------------------------------------------ 生命周期
def start(self):
self._running = True
threading.Thread(target=self._loop, daemon=True).start()
def stop(self):
self._running = False
self._kill_child()
def pause_preview(self):
self._preview_paused = True # 打印前释放 USB(不取新帧)
def resume_preview(self):
self._preview_paused = False
# ------------------------------------------------- 解码节流(v1.0.49)
# 现场 1080p 相机 30fps,每帧都要 JPEG 解码 ≈ 16ms(弱机 25~30ms),
# 一秒就是半个~整核,界面线程被抢得卡顿。而预览 90ms 一帧、识别只要
# 一张静帧,根本不需要 30fps 的解码 —— 所以只解最新一帧,其余丢掉。
def set_low_power(self, on):
"""拖动名单/翻页时把解码降到 ~3fps,CPU 让给界面"""
self._decode_gap = _DECODE_GAP_LOW if on else \
getattr(self, '_base_gap', _DECODE_GAP)
def decode_gap(self):
return getattr(self, '_decode_gap',
getattr(self, '_base_gap', _DECODE_GAP))
def _tune_gap(self):
"""按实测解码耗时定档(v1.0.52)。
原来看核数猜,可 Windows 的 os.cpu_count() 报的是逻辑核(i5-4200U
是 4),猜不出「这机器弱」。直接量:一帧 JPEG 解得越慢,就少解几帧。
配了 camera.decode_fps 的话以配置为准,不再自动改。
"""
if self._perf_fixed:
return
if self._tuned:
return
if self._frames_seen < 12: # 攒够十几帧再下结论,避开首帧冷启动
self._frames_seen += 1
return
self._tuned = True
ms = self.decode_ms
if ms >= 14.0:
self._base_gap = 0.17 # ≈6fps
elif ms >= 8.0:
self._base_gap = 0.125 # ≈8fps
else:
return
self.weak = True
self._decode_gap = self._base_gap
self.perf_note = ('解码一帧 %.1f ms(偏慢)→ 摄像头取帧降到 %.0f fps,'
'预览降到 6 fps 省 CPU' % (ms, 1.0 / self._base_gap))
# ------------------------------------------------------------ 热切换
def reconfigure(self, new_camera_cfg):
"""运行中切换摄像头配置(设置页选完立即生效,无需重启程序)"""
with self._lock:
self.cfg = dict(new_camera_cfg or {})
self._base_gap = default_decode_gap(self.cfg)
self._decode_gap = self._base_gap
self._reload = True
self.latest = None
self.error = None
self._bad = {} # 换设备/换配置后重新给所有设备机会
self.status = '正在切换摄像头…'
self._kill_child() # 杀掉旧取帧进程,循环会用新配置重开
def select_device(self, index, backend, width=None, height=None):
"""设置页选定某台设备:写入缓存(下次启动直开)并热切换。
现场只允许 USB 摄像头,非 USB(虚拟/内置/网络摄像头)直接拒绝。
"""
usb = usbcam.is_usb_index(index)
if usb is False:
raise ValueError(
'索引 %d(%s)不是 USB 摄像头,本机只允许使用 USB 摄像头'
% (int(index), usbcam.device_name(index) or '未知设备'))
name = usbcam.device_name(index)
self._save_cache(int(index), backend, int(width or 0),
int(height or 0), name)
cfg = dict(self.cfg)
cfg['simulate'] = False
cfg['index'] = int(index)
cfg['backend'] = backend
self.reconfigure(cfg)
return cfg
def device_name(self):
"""当前在用摄像头的名字(给界面显示)"""
op = self.opened
if not op:
return usbcam.device_name(int(self.cfg.get('index', 0)))
return op[4] if len(op) > 4 else usbcam.device_name(op[0])
def suspend(self):
"""临时停帧并释放摄像头(扫描设备前调用,避免设备被占用)"""
with self._lock:
self._suspended = True
self.status = '已暂停取帧(正在扫描设备)'
self._kill_child()
def resume(self):
"""恢复取帧"""
with self._lock:
self._suspended = False
self._kill_child() # 让循环立即按当前配置重连
# ------------------------------------------------------------ 取帧主循环
def _loop(self):
while self._running:
self._reload = False
if self.cfg.get('simulate'):
self._sim_loop()
else:
self._real_loop()
if not self._reload: # 非热切换退出则结束线程
break
def _real_loop(self):
"""取帧主循环:失败就换设备/换后端,全部试过就先歇一会再重来。
注:一台设备可能「DSHOW 40 秒打不开」,所以 tried 只在一次巡环内有效,
30 秒后清空重来——这样拔插 USB 恢复后不用重启程序也能自己接上。
"""
tried = set()
last_reset = time.monotonic()
while self._running and not self._reload:
if self._suspended:
time.sleep(0.3)
continue
if time.monotonic() - last_reset > RETRY_WINDOW_SEC:
tried.clear()
last_reset = time.monotonic()
dev = self._pick_device(tried)
if not dev:
time.sleep(2)
continue
key = (dev['index'], dev.get('backend', 'dshow'))
time.sleep(0.5) # 探测子进程刚释放设备,给驱动一点缓冲
self._refused = False
self._run_child(dev)
if self._refused: # 非 USB 被拒,直接弃用这台
tried.add(key)
if not self._running or self._reload:
break
tried.add(key) # 一次失败就换下一台/下一个后端,不再反复磨同一台
nm = usbcam.device_name(dev['index'])
if nm and not self._suspended:
self._bad[nm] = time.monotonic()
time.sleep(0.8)
@staticmethod
def _backend_for(idx, pref, tried):
"""该索引下一个该试的后端:配置优先,其次 dshow → msmf 轮换。
800 万像素模组常见「DSHOW 打不开、MSMF 能开」,所以不能死认一个后端;
每个 (索引, 后端) 组合各试一次,都失败才算这台设备废了。
"""
order = [pref] if pref in ('dshow', 'msmf', 'any') else []
order += [b for b in BACKEND_ORDER if b not in order]
for b in order:
if (int(idx), b) not in tried:
return b
return None
def _pick_device(self, tried):
"""挑选要打开的设备:显式选择 → 缓存 → 配置索引 → 扫描兜底。
优先用配置索引:正常现场只开一次设备,启动快且不折腾驱动;
只有它打不开时才扫描其它索引(扫描会把设备反复开关,某些驱动会卡)。
现场铁律:只开 USB 摄像头。usb_only 打开时,虚拟摄像头(手机投屏/
OBS/IP 摄像头)既不缓存也不兜底,直接跳过并给出可读原因。
"""
want_w = int(self.cfg.get('width', 0) or 0)
want_h = int(self.cfg.get('height', 0) or 0)
conf_idx = int(self.cfg.get('index', 0))
pref = str(self.cfg.get('backend', 'auto')).lower()
auto_pick = bool(self.cfg.get('auto_pick', True))
usb_only = self.cfg.get('usb_only', True)
self.diag = {} # 每轮重新收集,避免拿上一轮的原因误导现场
allowed, uinfo = (usbcam.usb_indices() if usb_only
else (None, None))
if usb_only and allowed is not None and not allowed:
with self._lock:
self.error = ('未检测到 USB 摄像头(%d 个非 USB 设备已被忽略)。'
'请把摄像头插到主机 USB 口而不是扩展坞,'
'并在设备管理器确认"照相机"下可见。'
% len(uinfo.get('ignored') or []))
self.status = self.error
return None
def ok(idx):
return allowed is None or int(idx) in allowed
def fresh(idx):
"""近期打不开的设备先跳过,免得每次开机都为它干等 40 秒"""
nm = usbcam.device_name(idx)
t = self._bad.get(nm)
return not t or (time.monotonic() - t) > BAD_TTL_SEC
def dev_for(idx, w=want_w, h=want_h):
if not ok(idx) or not fresh(idx):
return None
be = self._backend_for(idx, pref, tried)
if be is None:
return None
return {'index': int(idx), 'backend': be,
'width': int(w), 'height': int(h)}
# 0) 设置页显式选过的设备(按名字记),索引漂移也不怕
explicit = str(self.cfg.get('name') or '')
if explicit:
ni = usbcam.resolve_name(explicit)
if ni is not None:
d = dev_for(ni)
if d:
return d
# 1) 多台 USB 摄像头且没显式选过 → 优先外接那台(跳过像内置的)
if usb_only and allowed and len(allowed) > 1:
pi = usbcam.prefer_index(allowed)
if pi is not None:
d = dev_for(pi)
if d:
return d
# 2) 上次成功打开的(缓存里带名字,按名字重新定位索引)
cache = self._load_cache()
if cache:
ci = cache['index']
if cache.get('name'):
ri = usbcam.resolve_name(cache['name'])
if ri is not None:
ci = ri
be = self._backend_for(ci, cache.get('backend', pref), tried)
if be is not None and ok(ci) and fresh(ci):
return {'index': int(ci), 'backend': be,
'width': int(cache.get('width', want_w) or want_w),
'height': int(cache.get('height', want_h) or want_h)}
d = dev_for(conf_idx)
if d:
return d
if auto_pick:
scan_idxs = allowed if allowed is not None else None
if scan_idxs is not None:
scan_idxs = [i for i in scan_idxs
if self._backend_for(i, pref, tried) is not None]
if not scan_idxs:
scan_idxs = None if allowed is None else []
if scan_idxs is None or scan_idxs:
with self._lock:
self.status = ('摄像头 %d 不可用(非 USB 或打不开),'
'正在扫描 USB 摄像头…' % conf_idx)
found = discover_devices(
conf_idx, want_w or 1280, want_h or 720,
timeout=12.0 + 14.0 * len(scan_idxs or [1]),
indices=scan_idxs, diag=self.diag)
found.sort(key=lambda x: (x.get('height', 0),
x.get('width', 0)), reverse=True)
for x in found:
key = (int(x['index']), x.get('backend', 'dshow'))
if key in tried or not ok(x['index']):
continue
return {'index': key[0], 'backend': key[1],
'width': int(x.get('width', want_w) or want_w),
'height': int(x.get('height', want_h) or want_h)}
idxs = list(allowed) if allowed is not None else [conf_idx]
hint = diag_hint(self.diag, idxs)
if not hint:
hint = ('摄像头打不开(索引 %s,无画面):先确认没被微信/相机/浏览器'
'占用,再拔插一次 USB' % '、'.join(str(i) for i in idxs))
own = holder_hint()
if own:
hint += ';' + own
self._dbg('probe failed: %s' % hint)
with self._lock:
self.error = hint
self.status = self.error
return None
def _run_child(self, dev):
"""启动取帧子进程并消费管道;卡住/退出则返回让上层重开"""
af = self.cfg.get('autofocus', '')
if isinstance(af, bool):
af = '1' if af else '0'
else:
af = str(af or '').strip().lower()
af = {'true': '1', 'yes': '1', 'on': '1',
'false': '0', 'no': '0', 'off': '0'}.get(af, af)
if af not in ('0', '1'):
af = '' # 留空 = 不动驱动默认值
try:
focus = int(self.cfg.get('focus', -1))
except (TypeError, ValueError):
focus = -1
preset = ''
# 没指定固定焦距时,拿上次对好的焦距当起点(AF 仍开着,只是从近处起步)
if focus < 0 and self.cfg.get('focus_memo', True):
memo = self._memo_load()
if memo > 0:
focus = int(round(memo))
preset = '1'
cmd = _child_cmd('core.evidence._cam_child',
dev['index'], dev.get('backend', 'dshow'),
int(self.cfg.get('width', 0) or 0),
int(self.cfg.get('height', 0) or 0),
os.getpid(), af, focus, preset)
env = dict(os.environ)
env['PYTHONPATH'] = _ROOT + os.pathsep + env.get('PYTHONPATH', '')
with self._lock:
self.status = '正在打开摄像头(索引 %d)…' % dev['index']
try:
os.makedirs('data', exist_ok=True)
errf = open(os.path.join('data', 'cam_child_err.log'), 'ab')
proc = subprocess.Popen(cmd, cwd=_ROOT, env=env,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=errf)
self._dbg('spawn idx=%s backend=%s pid=%s'
% (dev['index'], dev.get('backend'), proc.pid))
except Exception as e:
with self._lock:
self.error = '无法启动取帧进程: %s' % e
return
self._proc = proc
_assign_to_job(proc)
q = queue.Queue()
# 最新一帧的槽位:相机 30fps,解码只要 13fps —— 旧帧直接丢,
# 免得队列越积越多(预览延迟好几秒 + 内存一直涨)。
slot = {'raw': None, 'notified': False}
def _reader(p, out):
try:
while True:
head = p.stdout.read(4)
if not head or len(head) < 4:
break
n = struct.unpack('<I', head)[0]
if n <= 0 or n > 20 * 1024 * 1024:
break
payload = p.stdout.read(n)
if not payload or len(payload) < n:
break
tag, body = payload[:1], payload[1:]
if tag == b'J':
out.put(('json', json.loads(body.decode('utf-8'))))
elif tag == b'F':
slot['raw'] = body # 只留最新,旧帧丢掉
if not slot['notified']:
slot['notified'] = True
out.put(('frame', None)) # 只发通知,不带数据
elif tag == b'S':
out.put(('status', json.loads(body.decode('utf-8'))))
except Exception:
pass
out.put(('eof', None))
threading.Thread(target=_reader, args=(proc, q), daemon=True).start()
last_msg = time.monotonic()
last_decode = 0.0
got_first = False
while self._running:
try:
kind, body = q.get(timeout=0.4)
except queue.Empty:
# 首条消息要等设备打开(2K 设备可能要 10 秒),之后按无帧超时判卡死
stall = CHILD_STALL_SEC if got_first else FIRST_MSG_SEC
if time.monotonic() - last_msg > stall:
with self._lock:
self.error = ('摄像头 %d 秒无响应,正在换设备'
% int(stall))
break
if proc.poll() is not None:
break
continue
last_msg = time.monotonic()
if kind == 'eof':
break
if kind == 'json':
got_first = True
if body.get('ok'):
self.focus_info = {'focus': body.get('focus'),
'autofocus': body.get('autofocus'),
'warm_frames': body.get('warm_frames')}
self._focus_locked = bool(body.get('focus_locked'))
self._dbg('opened %sx%s focus=%s af=%s warm=%s'
% (body.get('width'), body.get('height'),
body.get('focus'), body.get('autofocus'),
body.get('warm_frames')))
if not self._set_opened(body['index'],
body.get('backend', ''),
int(body['width']),
int(body['height'])):
break # 被拒(非 USB),别再从这台设备取帧
else:
self._dbg('child fail: %s' % body.get('error'))
with self._lock:
self.error = body.get('error', '摄像头异常')
self.status = self.error
self._drop_cache()
break
elif kind == 'status':
# 运行中的对焦状态(每秒一条):设置页显示、判断锁焦是否生效
info = dict(self.focus_info or {})
info.update({k: v for k, v in body.items()
if k in ('focus', 'autofocus')})
self.focus_info = info
# 记住"自动对焦找到的焦距":下次启动直接预置,AF 从近处起步
f, a = body.get('focus'), body.get('autofocus')
try:
if f and float(f) > 0 and (a is None or float(a) >= 0.5):
self._memo_save(float(f))
except (TypeError, ValueError):
pass
elif kind == 'frame':
body = slot['raw']
slot['raw'] = None
slot['notified'] = False
if not got_first:
got_first = True
if self._refused:
continue # 已判定非 USB,不用它的画面
if body is None:
continue
now = time.monotonic()
gap = self.decode_gap()
if now - last_decode < gap:
# 上一帧才解过,这帧丢掉;解码完 next 帧马上又来。
# 预览 90ms 一帧、识别只要一张最静的图,都够了。
continue
last_decode = now
_d0 = time.perf_counter()
img = cv2.imdecode(np.frombuffer(body, np.uint8),
cv2.IMREAD_COLOR)
_dt = (time.perf_counter() - _d0) * 1000.0
if self.decode_ms <= 0:
self.decode_ms = _dt
else:
self.decode_ms = self.decode_ms * 0.8 + _dt * 0.2
self._tune_gap()
if img is not None:
self._push(img)
with self._lock:
self.error = None
rc = proc.poll()
self._dbg('child exit rc=%s' % rc)
self._kill_child()
def _dbg(self, msg):
try:
with open(os.path.join('data', 'cam_debug.log'), 'a',
encoding='utf-8') as f:
f.write('%s %s\n' % (datetime.datetime.now().strftime(
'%H:%M:%S'), msg))
except Exception:
pass
def _kill_child(self):
p, self._proc = self._proc, None
if p is not None:
try:
p.kill()
except Exception:
pass
try:
p.wait(timeout=2)
except Exception:
pass
# ------------------------------------------------------------ 状态
def _set_opened(self, idx, bname, w, h):
"""打开成功回调;返回 False 表示被拒(非 USB 摄像头),调用方须停用"""
name = usbcam.device_name(idx)
if self.cfg.get('usb_only', True):
usb = usbcam.is_usb_index(idx)
if usb is False:
with self._lock:
self._refused = True
self.error = ('%d 号(%s)不是 USB 摄像头,已拒绝使用'
% (idx, name or '未知设备'))
self.status = self.error
self._drop_cache()
return False
self.opened = (idx, bname, w, h, name)
with self._lock:
self.error = None
self.status = '摄像头 %d%s(%s)%dx%d' % (
idx, ('·' + name) if name else '', bname, w, h)
self._bad.pop(name, None)
self._save_cache(idx, bname, w, h, name)
# 配置里写的档位这台设备不支持(8MP 模组很常见)→ 记下来让界面改配置,
# 否则下次启动又先撞一次南墙,白白多等十几秒
cw = int(self.cfg.get('width') or 0)
ch = int(self.cfg.get('height') or 0)
if cw > 0 and ch > 0 and (cw, ch) != (int(w), int(h)):
self.auto_size = {'width': int(w), 'height': int(h),
'from': '%dx%d' % (cw, ch)}
return True
def preview_status(self):
with self._lock:
if self.cfg.get('simulate'):
return '模拟摄像头(合成画面)'
if self.error:
return self.error
return self.status or '摄像头启动中…'
# ------------------------------------------------------------ 缓存
def _load_cache(self):
"""读缓存;缓存的设备若已不是 USB 摄像头(换了 USB 口/索引变了),弃用"""
try:
if os.path.exists(CACHE_PATH):
with open(CACHE_PATH, encoding='utf-8') as f:
d = json.load(f)
if isinstance(d, dict) and 'index' in d:
if self.cfg.get('usb_only', True):
if usbcam.is_usb_index(d['index']) is False:
self._drop_cache()
return None
return d
except Exception:
pass
return None
def _save_cache(self, idx, bname, w, h, name=''):
try:
os.makedirs(os.path.dirname(CACHE_PATH) or '.', exist_ok=True)
with open(CACHE_PATH, 'w', encoding='utf-8') as f:
json.dump({'index': idx, 'backend': bname,
'width': w, 'height': h, 'name': name or '',
'usb': True,
'saved_at': datetime.datetime.now().strftime(
'%Y-%m-%d %H:%M:%S')}, f, ensure_ascii=False)
except Exception:
pass
def _drop_cache(self):
try:
if os.path.exists(CACHE_PATH):
os.remove(CACHE_PATH)
except Exception:
pass
# ------------------------------------------------------------ 模拟画面
def _sim_loop(self):
self.status = '模拟摄像头(合成画面)'
n = 0
while self._running and not self._reload:
if self._suspended:
time.sleep(0.3)
continue
n += 1
img = np.full((720, 1280, 3), 244, dtype=np.uint8)
cv2.putText(img, 'SIM CAMERA seq=%d' % n, (400, 330),
cv2.FONT_HERSHEY_SIMPLEX, 1.2, (120, 120, 120), 3)
ts = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
cv2.putText(img, ts, (470, 390), cv2.FONT_HERSHEY_SIMPLEX,
0.8, (150, 150, 150), 2)
self._push(img)
time.sleep(0.2)
def _push(self, frame):
with self._lock:
self._seq += 1
self.latest = (self._seq, time.monotonic(), frame)
def get_frame(self):
with self._lock:
if self.latest is None:
return None, 0, 0.0
seq, arrived, img = self.latest
z = self.zoom
if z > 1.001:
img = self._zoom_frame(img, z)
return img.copy(), seq, arrived
# ------------------------------------------------------------ 数字变焦
def _zoom_frame(self, img, z=None):
"""中心裁剪 = 数字变焦(不动摄像头,只取中间一块)
UVC 摄像头的硬件变焦(CAP_PROP_ZOOM)绝大多数模组不支持,所以走
软件裁剪:预览、AI 识别照片、留档照片都用同一块,所见即所得。
好处不只是"看着近"——主体占的像素多了,对比度对焦更容易锁住它,
视觉模型也更容易认(现场取景偏窄/偏乱时尤其明显)。
"""
z = self.zoom if z is None else z
if img is None or z <= 1.001:
return img
h, w = img.shape[:2]
cw, ch = max(16, int(round(w / z))), max(16, int(round(h / z)))
x0, y0 = (w - cw) // 2, (h - ch) // 2
return img[y0:y0 + ch, x0:x0 + cw]
def set_zoom(self, z):
"""设置画面缩放倍数(1.0~4.0),返回实际生效值"""
try:
z = float(z)
except (TypeError, ValueError):
z = 1.0
z = max(1.0, min(4.0, z))
with self._lock:
self.zoom = z
self.cfg['zoom'] = z
return z
# ------------------------------------------------------------ 对焦提速
def poke_focus(self):
"""催一下自动对焦:让相机立刻重新找焦,而不是等它自己察觉画面变了
UVC 的连续 AF 有 0.3~0.8 秒的"反应过来"延迟,放完货不戳它,
多数时间浪费在这段等待上。已锁焦时不必戳(锁死反而更快)。
两条通道:stdin 单字节(开发模式/有控制台),文件信号(打包成
无控制台程序后的兜底)。
"""
if self._focus_locked:
return False
ok = False
p = self._proc
if p is not None and p.poll() is None:
try:
p.stdin.write(b'F')
p.stdin.flush()
ok = True
except Exception:
ok = False
if not ok:
try:
os.makedirs('data', exist_ok=True)
with open(os.path.join('data', 'focus_poke'), 'w'):
pass
ok = True
except Exception:
ok = False
return ok
def _memo_path(self):
return os.path.join('data', 'camera_focus.json')
def _memo_load(self):
"""上次对好的焦距(新会话开局直接预置,省掉一轮搜索)"""
try:
with open(self._memo_path(), 'r', encoding='utf-8') as f:
d = json.load(f)
v = float(d.get('focus'))
return v if v > 0 else -1.0
except Exception:
return -1.0
def _memo_save(self, focus):
now = time.monotonic()
if now - self._memo_at < 5.0: # 5 秒一次,别把磁盘写满
return
self._memo_at = now
try:
os.makedirs('data', exist_ok=True)
with open(self._memo_path(), 'w', encoding='utf-8') as f:
json.dump({'focus': round(float(focus), 2),
'device': self.device_name(),
'at': datetime.datetime.now().isoformat(
timespec='seconds')}, f, ensure_ascii=False)
except Exception:
pass
@staticmethod
def sharpness(img):
"""清晰度(灰度拉普拉斯的方差):越大越清楚,用来判对焦有没有收敛"""
try:
g = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
h, w = g.shape[:2]
if w > 320:
g = cv2.resize(g, (320, max(1, int(h * 320.0 / w))))
return float(cv2.Laplacian(g, cv2.CV_64F).var())
except Exception:
return 0.0
def wait_focus(self, timeout_ms=800, step=0.06):
"""等自动对焦收敛后再取帧(返回诊断信息 + 最清晰的那一帧)。
为什么需要:这类 UVC 相机是"对比度对焦",放货后要 0.5~2 秒边看边找焦,
这段时间画面是糊的。旧代码在重量刚稳定(约 0.2 秒后)就抓图当识别输入,
等于专挑最糊的一帧 —— 现场感觉"焦距调得很慢",AI 也常认不出。
判据不设绝对阈值(不同货品/光照差异太大),只看清晰度是否已经到过峰值
附近并且连续几帧不再明显变化;超时就按**最清晰的那一帧**用,
而不是最后一帧(最后一帧可能刚好在 AF 回落途中)。
"""
t0 = time.monotonic()
with self._lock:
start_seq = self.latest[0] if self.latest else 0
deadline = t0 + max(0.25, float(timeout_ms) / 1000.0)
scores = []
last_seq = start_seq
best_img, best_score, best_seq = None, 0.0, start_seq
while time.monotonic() < deadline:
with self._lock:
latest = self.latest
z = self.zoom
if latest is None:
time.sleep(step)
continue
seq, arrived, img = latest
# 只统计"新到的帧":同一帧重复采样会得出"没变化"的假结论
if seq <= last_seq or (time.monotonic() - arrived) > 0.5:
time.sleep(step)
continue
last_seq = seq
view = self._zoom_frame(img, z) # 与送识别的画面保持一致
s = self.sharpness(view)
if s > best_score:
best_score, best_img, best_seq = s, view, seq
scores.append(s)
if len(scores) > 6:
scores = scores[-6:]
# 最近 3 帧清晰度基本不变(相差 ≤10%)且已达到本次峰值的 70%
# → 对焦停住了。后者防的是"刚起步两帧都糊"被误判为收敛。
if len(scores) >= 3 and best_score > 0:
recent = scores[-3:]
hi, lo = max(recent), min(recent)
if (hi - lo) <= 0.10 * hi and recent[-1] >= 0.70 * best_score:
return {'settled': True, 'sharp': round(s, 1),
'waited_ms': int((time.monotonic() - t0) * 1000),
'frame': best_img, 'seq': best_seq}
time.sleep(step)
return {'settled': False,
'sharp': round(best_score, 1),
'waited_ms': int((time.monotonic() - t0) * 1000),
'frame': best_img, 'seq': best_seq}
def ready(self, max_age_ms=1500):
"""是否已有可用画面(摄像头刚打开/切换时还没有帧)
现场用:4K 摄像头从打开到出帧要 5~8 秒,这段时间不要让流程
起抓拍(否则每 400ms 失败一次,日志被「无摄像头画面」刷屏)。
"""
with self._lock:
if self.latest is None:
return False
_, arrived, _ = self.latest
return (time.monotonic() - arrived) * 1000.0 <= max_age_ms
# ------------------------------------------------------------ 识别帧
def snapshot_recognition(self, max_px=1280, quality=88,
wait_focus=False):
# 先等自动对焦收敛(刚放货时相机正在找焦,这一帧直接决定 AI 认不认得出)
frame = None
if wait_focus:
info = self.wait_focus(
float(self.cfg.get('focus_wait_ms', 800) or 0))
self.last_focus_wait = info
if info and not info.get('settled'):
self._dbg('focus not settled in %sms (sharp=%.1f)'
% (info.get('waited_ms'), info.get('sharp') or 0))
# 用等待期间**最清晰**的那一帧,而不是刚好停在最后一帧
frame = (info or {}).get('frame')
if frame is None:
frame, _, _ = self.get_frame()
if frame is None:
return None
h, w = frame.shape[:2]
long_edge = max(h, w)
if max_px and long_edge > max_px:
r = max_px / float(long_edge)
frame = cv2.resize(frame, (int(w * r), int(h * r)),
interpolation=cv2.INTER_AREA)
path = self._save(frame, quality)
return path
# ------------------------------------------------------------ 留档新帧
def capture_confirmed(self):
req_seq = self.latest[0] if self.latest else 0
req_at = time.monotonic()
reason = None
for _ in range(ARCHIVE_MAX_ATTEMPTS):
time.sleep(0.15)
with self._lock:
if self.latest is None:
reason = '无画面'
continue
seq, arrived, img = self.latest
new_frames = seq - req_seq
age_ms = (time.monotonic() - arrived) * 1000.0
if seq <= req_seq:
reason = '等待新帧'
continue
if new_frames < CONFIRMED_MIN_NEW_FRAMES:
reason = '新帧不足'
continue
if arrived <= req_at:
reason = '帧早于请求'
continue
if age_ms > MAX_CAPTURE_FRAME_AGE_MS:
reason = '帧龄过期'
continue
z = self.zoom
if z > 1.001: # 留档照片跟预览同视角(放大后更清楚)
img = self._zoom_frame(img, z)
path = self._save(img, 90)
with open(path, 'rb') as f:
sha = hashlib.sha256(f.read()).hexdigest()
return {'qualified': True, 'path': path, 'frame_seq': seq,
'arrived': arrived, 'requested_at': req_at,
# 墙钟拍摄时间:分拣照片上传要带 captured_at(安卓同样带)
'captured_at': time.time(),
'sha256': sha, 'reason': None}
return {'qualified': False, 'path': None, 'frame_seq': 0,
'arrived': 0.0, 'requested_at': req_at, 'captured_at': 0.0,
'sha256': '', 'reason': reason or '重试超限'}
def _save(self, frame, quality):
d = self._snap_target()
os.makedirs(d, exist_ok=True)
name = datetime.datetime.now().strftime(
'%Y%m%d_%H%M%S_%f')[:-3] + '.jpg'
path = os.path.join(d, name)
# cv2.imwrite 在 Windows 上走 fopen,路径里有中文(D:\入库分拣抓拍)
# 会静默失败:返回 False、文件不存在,流程却以为拍到了。改成先编码
# 再用 Python 的 open 写(宽字符 API,中文路径没问题)。
try:
ok, buf = cv2.imencode(
'.jpg', frame, [int(cv2.IMWRITE_JPEG_QUALITY), int(quality)])
if ok:
with open(path, 'wb') as f:
f.write(buf.tobytes())
if os.path.getsize(path) > 0:
return path
except Exception: # noqa: BLE001
pass
# 编码失败(或写失败)时退回 imwrite:ASCII 路径下它没问题
cv2.imwrite(path, frame, [cv2.IMWRITE_JPEG_QUALITY, quality])
return path
def _snap_target(self):
"""确认抓拍目录可写,返回真正要用的目录。
D 盘没插、盘符变了、权限被策略挡掉 —— 这些都不该让过秤停下来:
回退到程序目录的 data/snapshots,只写一条说明。
"""
if self._snap_ready:
return self.snap_dir
if _dir_writable(self.snap_dir):
self._snap_ready = True
return self.snap_dir
fb = os.path.join(_ROOT, 'data', 'snapshots')
if self.snap_dir != fb and _dir_writable(fb):
self.snap_note = ('抓拍目录 %s 不可写,已改存 %s'
% (self.snap_dir, fb))
self.snap_dir = fb
self._snap_ready = True
return fb
# 两边都不行也别在这里炸:让 imwrite 报错走原来的失败分支
self._snap_ready = True
return self.snap_dir