Files

99 lines
3.5 KiB
Python

# -*- coding: utf-8 -*-
"""摄像头模块(免驱动 UVC 摄像头,DirectShow 后端)
- 后台线程持续取帧,供界面预览
- snapshot() 保存一帧到 JPEG(用原始分辨率 2K 截图)
- simulate=True 时生成模拟画面,便于无摄像头调试
"""
import os
import time
import datetime
import threading
import cv2
class Camera:
def __init__(self, cfg):
self.cfg = cfg.get('camera', {})
self.latest = None # 最新一帧 (BGR)
self.error = None
self._lock = threading.Lock()
self._running = False
def start(self):
self._running = True
threading.Thread(target=self._loop, daemon=True).start()
def stop(self):
self._running = False
def _loop(self):
if self.cfg.get('simulate'):
self._sim_loop()
return
cap = None
while self._running:
try:
if cap is None or not cap.isOpened():
cap = cv2.VideoCapture(int(self.cfg.get('index', 0)), cv2.CAP_DSHOW)
# 2K 分辨率通常需要 MJPG 才能稳定出流
cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*'MJPG'))
cap.set(cv2.CAP_PROP_FRAME_WIDTH, int(self.cfg.get('width', 2560)))
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, int(self.cfg.get('height', 1440)))
with self._lock:
self.error = None if cap.isOpened() else '摄像头打开失败'
if not cap.isOpened():
time.sleep(3)
continue
ok, frame = cap.read()
if ok:
with self._lock:
self.latest = frame
else:
time.sleep(0.05)
except Exception as e:
with self._lock:
self.error = str(e)
time.sleep(3)
def _sim_loop(self):
while self._running:
import numpy as np
img = np.full((720, 1280, 3), 245, dtype=np.uint8)
cv2.putText(img, 'SIM CAMERA (no device)', (330, 340),
cv2.FONT_HERSHEY_SIMPLEX, 1.4, (120, 120, 120), 3)
ts = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
cv2.putText(img, ts, (480, 400), cv2.FONT_HERSHEY_SIMPLEX, 0.8,
(150, 150, 150), 2)
with self._lock:
self.latest = img
time.sleep(0.2)
def get_frame(self):
with self._lock:
return None if self.latest is None else self.latest.copy()
def snapshot(self, max_px=None):
"""保存当前帧,返回文件路径;无画面返回 None。
max_px: 识别用图可传 1280,将长边降采样后再存——
云端识别不需要 2K 原图,可显著缩短上传与推理时间。
"""
frame = self.get_frame()
if frame is None:
return None
if max_px:
h, w = frame.shape[:2]
long_edge = max(h, w)
if long_edge > max_px:
ratio = max_px / float(long_edge)
frame = cv2.resize(frame, (int(w * ratio), int(h * ratio)),
interpolation=cv2.INTER_AREA)
d = 'data/snapshots'
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(path, frame, [cv2.IMWRITE_JPEG_QUALITY, 88])
return path