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

303 lines
11 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 -*-
"""摄像头取帧子进程:打开设备 → 读帧 → JPEG 编码 → 管道输出。
单独成进程的原因:cv2.VideoCapture 在部分 Windows 驱动上会无限期阻塞
(DSHOW 打不开时会卡满 40 秒),主进程无法中断。放到子进程后父进程可以
用「长时间无帧就 kill」的方式兜住,界面永远不会假死。
分辨率策略(800 万像素模组实测需要)
------------------------------------
8MP 模组通常只提供 3264×2448 / 2592×1944 / 1920×1080 / 1280×720 这几档,
硬要它给 2560×1440 会直接打开失败或一帧都不出。所以这里不再「只认配置值」,
而是按 want → 3264×2448 → 2592×1944 → 2560×1440 → 1920×1080 → 1280×720
逐档尝试,哪档能出画面就用哪档,并把实际分辨率回报给父进程。
协议(每条消息 = 4 字节小端长度 + 载荷):
b'J' + json_bytes 状态消息(打开成功/失败、实际分辨率)
b'F' + jpeg_bytes 一帧画面
"""
import sys
import os
import json
import time
import struct
import threading
import cv2
BACKENDS = {'dshow': cv2.CAP_DSHOW, 'msmf': cv2.CAP_MSMF,
'any': cv2.CAP_ANY}
# 常见 USB 摄像头档位:8MP 原生 → 5MP → 2K → 1080P → 720P
SIZE_CHAIN = ((3264, 2448), (2592, 1944), (2560, 1440),
(1920, 1080), (1280, 720))
def size_chain(want_w=0, want_h=0):
"""配置优先,其后按常见档位逐级回退(去重)"""
out = []
if int(want_w or 0) > 0 and int(want_h or 0) > 0:
out.append((int(want_w), int(want_h)))
for s in SIZE_CHAIN:
if s not in out:
out.append(s)
return out
def _watch_parent(parent_pid):
"""父进程一旦退出,立刻释放摄像头并退出,避免孤儿进程占着设备"""
try:
import ctypes
k32 = ctypes.windll.kernel32
SYNCHRONIZE = 0x00100000
h = k32.OpenProcess(SYNCHRONIZE, False, int(parent_pid))
if not h:
os._exit(0)
while True:
if k32.WaitForSingleObject(h, 1000) == 0: # 已退出
os._exit(0)
except Exception:
pass
def send(payload):
sys.stdout.buffer.write(struct.pack('<I', len(payload)) + payload)
sys.stdout.buffer.flush()
def send_json(obj):
send(b'J' + json.dumps(obj, ensure_ascii=False).encode('utf-8'))
def _grab_first(cap, sizes, tries_per_size=12, wait=0.1):
"""按档位逐级试,返回 (frame, (w, h)) 或 (None, None)"""
for w, h in sizes:
try:
cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*'MJPG'))
cap.set(cv2.CAP_PROP_FRAME_WIDTH, int(w))
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, int(h))
except Exception:
pass
for _ in range(tries_per_size):
try:
ok, f = cap.read()
except Exception:
ok, f = False, None
if ok and f is not None and getattr(f, 'size', 0):
return f, (w, h)
time.sleep(wait)
return None, None
def _apply_focus(cap, autofocus, focus, preset=False):
"""对焦设置:AF 交给驱动(默认),或锁死在固定焦距(固定工位不来回找焦)
· autofocus='1' / '0':显式打开/关闭连续自动对焦;留空=不动驱动默认值。
· focus>=0 时先关 AF 再写焦距值(顺序反了会被 AF 立刻覆盖)。
· preset=True:写完焦距再**把 AF 打开**——等于"从上次对好的位置起步,
再让相机微调"。比从无穷远重新扫一遍快得多(现场 1.5s → 0.3s 量级)。
返回实际读回的值,便于现场判断这台相机认不认这两个属性(不认会读回 0)。
"""
got_af, got_focus = None, None
try:
if autofocus in ('0', '1'):
cap.set(cv2.CAP_PROP_AUTOFOCUS, 1 if autofocus == '1' else 0)
if focus is not None and focus >= 0:
cap.set(cv2.CAP_PROP_AUTOFOCUS, 0)
cap.set(cv2.CAP_PROP_FOCUS, int(focus))
if preset:
time.sleep(0.05)
cap.set(cv2.CAP_PROP_AUTOFOCUS, 1)
got_af = cap.get(cv2.CAP_PROP_AUTOFOCUS)
got_focus = cap.get(cv2.CAP_PROP_FOCUS)
except Exception:
pass
return {'autofocus': got_af, 'focus': got_focus}
def _poke_focus(cap):
"""催一次自动对焦:AF 关一下再开,驱动会立刻重新走一遍找焦
不催的话,连续 AF 要自己察觉画面变了才动,白等 0.3~0.8 秒。
"""
try:
cap.set(cv2.CAP_PROP_AUTOFOCUS, 0)
time.sleep(0.03)
cap.set(cv2.CAP_PROP_AUTOFOCUS, 1)
return True
except Exception:
return False
def _command_loop(cap, lock):
"""父进程通过 stdin 发单字节命令:'F' = 催对焦(能通就用,不通走文件)"""
try:
stream = getattr(sys.stdin, 'buffer', None) if sys.stdin else None
if stream is None:
return
while True:
ch = stream.read(1)
if not ch:
break
if ch == b'F':
with lock:
_poke_focus(cap)
except Exception:
pass
POKE_FILE = os.path.join('data', 'focus_poke')
def _poke_loop(cap, lock):
"""文件信号兜底:打包成无控制台程序后子进程可能没有 stdin。
父进程放一个 data/focus_poke 文件,这里 0.2 秒看一眼,有就删掉并催对焦。
"""
while True:
time.sleep(0.2)
try:
if os.path.exists(POKE_FILE):
try:
os.remove(POKE_FILE)
except Exception:
pass
with lock:
_poke_focus(cap)
except Exception:
pass
def send_status(obj):
"""运行中的对焦状态('S' 消息):设置页显示当前焦距、判断锁焦是否生效"""
try:
send(b'S' + json.dumps(obj).encode('utf-8'))
except Exception:
pass
def main():
idx = int(sys.argv[1]) if len(sys.argv) > 1 else 0
bname = sys.argv[2] if len(sys.argv) > 2 else 'dshow'
want_w = int(sys.argv[3]) if len(sys.argv) > 3 else 0
want_h = int(sys.argv[4]) if len(sys.argv) > 4 else 0
autofocus = sys.argv[6] if len(sys.argv) > 6 else ''
try:
focus = int(sys.argv[7]) if len(sys.argv) > 7 else -1
except ValueError:
focus = -1
preset = (sys.argv[8] if len(sys.argv) > 8 else '') == '1'
if len(sys.argv) > 5:
try:
threading.Thread(target=_watch_parent, args=(sys.argv[5],),
daemon=True).start()
except Exception:
pass
cap = None
try:
cap = cv2.VideoCapture(idx, BACKENDS.get(bname, cv2.CAP_DSHOW))
if not cap.isOpened():
send_json({'ok': False,
'error': '设备打不开(索引 %d,%s):可能被其它程序占用,'
'或设备已挂死,请拔插一次摄像头 USB'
% (idx, bname)})
return 2
try:
cap.set(cv2.CAP_PROP_OPEN_TIMEOUT_MSEC, 4000)
cap.set(cv2.CAP_PROP_READ_TIMEOUT_MSEC, 2000)
except Exception:
pass
sizes = size_chain(want_w, want_h)
frame, used = _grab_first(cap, sizes, tries_per_size=12, wait=0.1)
if frame is None:
send_json({'ok': False,
'error': '设备已打开但一帧画面都没有(索引 %d,%s):'
'驱动/固件卡住,请拔插摄像头 USB 后重试;'
'若仍无画面,把"摄像头宽/高"改成 0 让它自动选档'
% (idx, bname)})
return 3
h, w = frame.shape[:2]
fwinfo = _apply_focus(cap, autofocus, focus, preset)
cap_lock = threading.Lock()
try:
os.remove(POKE_FILE) # 清掉上次残留,避免一开机就催
except Exception:
pass
for fn in (_command_loop, _poke_loop):
try:
threading.Thread(target=fn, args=(cap, cap_lock),
daemon=True).start()
except Exception:
pass
# 预热:对比度对焦是"边看边找",刚出图时画面通常是糊的,要 0.5~2 秒才收敛。
# 先空转约 1 秒(并且至少 8 帧)再报就绪,免得登录后第一件货拍到的
# 是正在找焦的糊图(AI 识别也跟着失败)。
warm_end = time.monotonic() + 1.0
hard_end = time.monotonic() + 3.0
warm_n = 0
while time.monotonic() < hard_end:
if warm_n >= 8 and time.monotonic() >= warm_end:
break
try:
ok, f = cap.read()
except Exception:
ok, f = False, None
if ok and f is not None:
warm_n += 1
else:
time.sleep(0.02)
send_json({'ok': True, 'index': idx, 'backend': bname,
'width': int(w), 'height': int(h),
'warm_frames': warm_n,
'focus': fwinfo.get('focus'),
'autofocus': fwinfo.get('autofocus'),
'focus_locked': focus >= 0 and not preset,
'sizes_tried': len(sizes)})
fails = 0
last_status = 0.0
while True:
with cap_lock:
ok, f = cap.read()
if ok and f is not None and getattr(f, 'size', 0):
fails = 0
ok2, buf = cv2.imencode('.jpg', f,
[cv2.IMWRITE_JPEG_QUALITY, 82])
if ok2:
send(b'F' + buf.tobytes())
now = time.monotonic()
# 0.25 秒报一次对焦状态:父进程要靠它判断"焦距是不是不动了",
# 1 秒一次太粗,等收敛时会白等
if now - last_status >= 0.25:
last_status = now
try:
send_status({'focus': cap.get(cv2.CAP_PROP_FOCUS),
'autofocus':
cap.get(cv2.CAP_PROP_AUTOFOCUS)})
except Exception:
pass
continue
fails += 1
if fails > 100: # 连续 10 秒读不到 → 退出让父进程重开
send_json({'ok': False, 'error': '读帧连续失败,重启设备'})
return 4
time.sleep(0.02)
except Exception as e: # noqa: BLE001
try:
send_json({'ok': False, 'error': '取帧异常: %s' % e})
except Exception:
pass
return 5
finally:
if cap is not None:
try:
cap.release()
except Exception:
pass
if __name__ == '__main__':
sys.exit(main() or 0)