panorama_camera.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. """
  2. 全景摄像头模块
  3. 负责获取视频流和物体检测
  4. """
  5. import cv2
  6. import numpy as np
  7. import threading
  8. import queue
  9. import time
  10. import os
  11. from typing import Optional, List, Tuple, Dict, Any
  12. from dataclasses import dataclass
  13. from config import PANORAMA_CAMERA, DETECTION_CONFIG
  14. from dahua_sdk import DahuaSDK, PTZCommand
  15. @dataclass
  16. class DetectedObject:
  17. """检测到的物体"""
  18. class_name: str # 类别名称
  19. confidence: float # 置信度
  20. bbox: Tuple[int, int, int, int] # 边界框 (x, y, width, height)
  21. center: Tuple[int, int] # 中心点坐标
  22. track_id: Optional[int] = None # 跟踪ID
  23. class PanoramaCamera:
  24. """全景摄像头类"""
  25. def __init__(self, sdk: DahuaSDK, camera_config: Dict = None):
  26. """
  27. 初始化全景摄像头
  28. Args:
  29. sdk: 大华SDK实例
  30. camera_config: 摄像头配置
  31. """
  32. self.sdk = sdk
  33. self.config = camera_config or PANORAMA_CAMERA
  34. self.login_handle = None
  35. self.play_handle = None
  36. self.connected = False
  37. # 视频流
  38. self.frame_queue = queue.Queue(maxsize=10)
  39. self.current_frame = None
  40. self.frame_lock = threading.Lock()
  41. self.rtsp_cap = None # RTSP视频捕获
  42. # 检测器
  43. self.detector = None
  44. # 控制标志
  45. self.running = False
  46. self.stream_thread = None
  47. # 断线重连
  48. self.auto_reconnect = True
  49. self.reconnect_interval = 5.0 # 重连间隔(秒)
  50. self.max_reconnect_attempts = 3 # 最大重连次数
  51. def connect(self) -> bool:
  52. """
  53. 连接摄像头
  54. Returns:
  55. 是否成功
  56. """
  57. login_handle, error = self.sdk.login(
  58. self.config['ip'],
  59. self.config['port'],
  60. self.config['username'],
  61. self.config['password']
  62. )
  63. if login_handle is None:
  64. print(f"连接全景摄像头失败: IP={self.config['ip']}, 错误码={error}")
  65. return False
  66. self.login_handle = login_handle
  67. self.connected = True
  68. print(f"成功连接全景摄像头: {self.config['ip']}")
  69. return True
  70. def disconnect(self):
  71. """断开连接"""
  72. self.stop_stream()
  73. if self.login_handle:
  74. self.sdk.logout(self.login_handle)
  75. self.login_handle = None
  76. self.connected = False
  77. def start_stream(self) -> bool:
  78. """
  79. 开始视频流
  80. Returns:
  81. 是否成功
  82. """
  83. if not self.connected:
  84. return False
  85. self.play_handle = self.sdk.real_play(
  86. self.login_handle,
  87. self.config['channel']
  88. )
  89. if self.play_handle is None:
  90. print("启动视频流失败")
  91. return False
  92. self.running = True
  93. self.stream_thread = threading.Thread(target=self._stream_worker, daemon=True)
  94. self.stream_thread.start()
  95. print("视频流已启动")
  96. return True
  97. def start_stream_rtsp(self, rtsp_url: str = None) -> bool:
  98. """
  99. 通过RTSP协议获取视频流
  100. Args:
  101. rtsp_url: RTSP地址,格式: rtsp://user:pass@ip:port/channel
  102. Returns:
  103. 是否成功
  104. """
  105. if rtsp_url is None:
  106. # 构建RTSP地址
  107. rtsp_url = f"rtsp://{self.config['username']}:{self.config['password']}@{self.config['ip']}:{self.config.get('rtsp_port', 554)}/h264/ch{self.config['channel']}/main/av_stream"
  108. try:
  109. self.rtsp_cap = cv2.VideoCapture(rtsp_url)
  110. if not self.rtsp_cap.isOpened():
  111. print(f"无法打开RTSP流: {rtsp_url}")
  112. return False
  113. self.running = True
  114. self.stream_thread = threading.Thread(target=self._rtsp_stream_worker, daemon=True)
  115. self.stream_thread.start()
  116. print(f"RTSP视频流已启动: {rtsp_url}")
  117. return True
  118. except Exception as e:
  119. print(f"RTSP流启动失败: {e}")
  120. return False
  121. def _stream_worker(self):
  122. """视频流工作线程 (SDK模式)"""
  123. retry_count = 0
  124. max_retries = 10
  125. while self.running:
  126. try:
  127. # 尝试从 SDK 帧缓冲区获取帧 (如果可用)
  128. frame_buffer = self.sdk.get_video_frame_buffer(self.config['channel'])
  129. if frame_buffer:
  130. frame_info = frame_buffer.get(timeout=0.1)
  131. if frame_info and frame_info.get('data'):
  132. # 解码帧数据 (如果需要)
  133. # 注意: SDK回调返回的是编码数据,需要解码
  134. # 这里暂时跳过,因为解码需要额外处理
  135. pass
  136. # RTSP 模式获取帧 (推荐方式)
  137. if self.rtsp_cap is not None and self.rtsp_cap.isOpened():
  138. ret, frame = self.rtsp_cap.read()
  139. if ret and frame is not None:
  140. with self.frame_lock:
  141. self.current_frame = frame.copy()
  142. try:
  143. self.frame_queue.put(frame.copy(), block=False)
  144. except queue.Full:
  145. pass
  146. retry_count = 0 # 重置重试计数
  147. time.sleep(0.001) # 减少CPU占用
  148. continue
  149. # 如果 RTSP 不可用,尝试自动连接
  150. if retry_count < max_retries:
  151. rtsp_url = self._build_rtsp_url()
  152. try:
  153. if self.rtsp_cap is None:
  154. self.rtsp_cap = cv2.VideoCapture(rtsp_url)
  155. self.rtsp_cap.set(cv2.CAP_PROP_BUFFERSIZE, 1) # 减少缓冲延迟
  156. if self.rtsp_cap.isOpened():
  157. retry_count = 0
  158. continue
  159. except Exception as e:
  160. pass
  161. retry_count += 1
  162. time.sleep(1.0) # 重试间隔
  163. else:
  164. # 超过最大重试次数,使用模拟帧
  165. frame = np.zeros((1080, 1920, 3), dtype=np.uint8)
  166. with self.frame_lock:
  167. self.current_frame = frame
  168. try:
  169. self.frame_queue.put(frame, block=False)
  170. except queue.Full:
  171. pass
  172. time.sleep(0.1)
  173. except Exception as e:
  174. print(f"视频流错误: {e}")
  175. time.sleep(0.1)
  176. def _build_rtsp_url(self) -> str:
  177. """构建 RTSP URL"""
  178. return f"rtsp://{self.config['username']}:{self.config['password']}@{self.config['ip']}:{self.config.get('rtsp_port', 554)}/h264/ch{self.config['channel']}/main/av_stream"
  179. def _rtsp_stream_worker(self):
  180. """RTSP视频流工作线程"""
  181. while self.running:
  182. try:
  183. if self.rtsp_cap is None or not self.rtsp_cap.isOpened():
  184. time.sleep(0.1)
  185. continue
  186. ret, frame = self.rtsp_cap.read()
  187. if not ret or frame is None:
  188. time.sleep(0.01)
  189. continue
  190. with self.frame_lock:
  191. self.current_frame = frame.copy()
  192. try:
  193. self.frame_queue.put(frame, block=False)
  194. except queue.Full:
  195. pass
  196. except Exception as e:
  197. print(f"RTSP视频流错误: {e}")
  198. time.sleep(0.1)
  199. def stop_stream(self):
  200. """停止视频流"""
  201. self.running = False
  202. if self.stream_thread:
  203. self.stream_thread.join(timeout=2)
  204. if self.play_handle:
  205. self.sdk.stop_real_play(self.play_handle)
  206. self.play_handle = None
  207. if self.rtsp_cap:
  208. self.rtsp_cap.release()
  209. self.rtsp_cap = None
  210. def get_frame(self) -> Optional[np.ndarray]:
  211. """
  212. 获取当前帧
  213. Returns:
  214. 当前帧图像
  215. """
  216. with self.frame_lock:
  217. return self.current_frame.copy() if self.current_frame is not None else None
  218. def get_frame_from_queue(self, timeout: float = 0.1) -> Optional[np.ndarray]:
  219. """
  220. 从帧队列获取帧 (用于批量处理)
  221. Args:
  222. timeout: 等待超时时间
  223. Returns:
  224. 帧图像或None
  225. """
  226. try:
  227. return self.frame_queue.get(timeout=timeout)
  228. except:
  229. return None
  230. def get_frame_buffer(self, count: int = 5) -> List[np.ndarray]:
  231. """
  232. 获取帧缓冲 (用于运动检测等需要多帧的场景)
  233. Args:
  234. count: 获取帧数
  235. Returns:
  236. 帧列表
  237. """
  238. frames = []
  239. while len(frames) < count:
  240. frame = self.get_frame_from_queue(timeout=0.05)
  241. if frame is not None:
  242. frames.append(frame)
  243. else:
  244. break
  245. return frames
  246. def set_detector(self, detector):
  247. """设置物体检测器"""
  248. self.detector = detector
  249. def detect_objects(self, frame: np.ndarray = None) -> List[DetectedObject]:
  250. """
  251. 检测物体
  252. Args:
  253. frame: 输入帧,如果为None则使用当前帧
  254. Returns:
  255. 检测到的物体列表
  256. """
  257. if frame is None:
  258. frame = self.get_frame()
  259. if frame is None or self.detector is None:
  260. return []
  261. return self.detector.detect(frame)
  262. def get_detection_position(self, obj: DetectedObject,
  263. frame_size: Tuple[int, int]) -> Tuple[float, float]:
  264. """
  265. 获取检测物体在画面中的相对位置
  266. Args:
  267. obj: 检测到的物体
  268. frame_size: 画面尺寸 (width, height)
  269. Returns:
  270. 相对位置 (x_ratio, y_ratio) 范围0-1
  271. """
  272. width, height = frame_size
  273. x_ratio = obj.center[0] / width
  274. y_ratio = obj.center[1] / height
  275. return (x_ratio, y_ratio)
  276. class ObjectDetector:
  277. """
  278. 物体检测器
  279. 使用YOLO11模型进行人体检测
  280. 支持 YOLO (.pt), RKNN (.rknn), ONNX (.onnx) 模型
  281. """
  282. def __init__(self, model_path: str = None, use_gpu: bool = True, model_size: str = 'n',
  283. model_type: str = 'auto'):
  284. """
  285. 初始化检测器
  286. Args:
  287. model_path: 模型路径 (支持 .pt, .rknn, .onnx)
  288. use_gpu: 是否使用GPU
  289. model_size: 模型尺寸 ('n', 's', 'm', 'l', 'x') - 仅 YOLO 模型有效
  290. model_type: 模型类型 ('auto', 'yolo', 'rknn', 'onnx')
  291. """
  292. self.model = None
  293. self.rknn_detector = None
  294. self.model_path = model_path
  295. self.use_gpu = use_gpu
  296. self.model_size = model_size
  297. self.model_type = model_type
  298. self.config = DETECTION_CONFIG
  299. self.device = 'cuda:0' if use_gpu else 'cpu'
  300. # 根据扩展名自动判断模型类型
  301. if model_path:
  302. ext = os.path.splitext(model_path)[1].lower()
  303. if ext == '.rknn':
  304. self.model_type = 'rknn'
  305. elif ext == '.onnx':
  306. self.model_type = 'onnx'
  307. elif ext == '.pt':
  308. self.model_type = 'yolo'
  309. self._load_model()
  310. def _load_model(self):
  311. """加载检测模型"""
  312. if self.model_type == 'rknn':
  313. self._load_rknn_model()
  314. elif self.model_type == 'onnx':
  315. self._load_onnx_model()
  316. else:
  317. self._load_yolo_model()
  318. def _load_rknn_model(self):
  319. """加载 RKNN 模型"""
  320. if not self.model_path:
  321. raise ValueError("RKNN 模型需要指定 model_path")
  322. try:
  323. from rknnlite.api import RKNNLite
  324. self.rknn = RKNNLite()
  325. ret = self.rknn.load_rknn(self.model_path)
  326. if ret != 0:
  327. raise RuntimeError(f"加载 RKNN 模型失败: {self.model_path}")
  328. ret = self.rknn.init_runtime(core_mask=RKNNLite.NPU_CORE_0_1_2)
  329. if ret != 0:
  330. raise RuntimeError(f"初始化 RKNN 运行时失败")
  331. print(f"RKNN 模型加载成功: {self.model_path}")
  332. except ImportError:
  333. raise ImportError("未安装 rknnlite,请运行: pip install rknnlite2")
  334. def _load_onnx_model(self):
  335. """加载 ONNX 模型"""
  336. if not self.model_path:
  337. raise ValueError("ONNX 模型需要指定 model_path")
  338. try:
  339. import onnxruntime as ort
  340. self.session = ort.InferenceSession(self.model_path)
  341. self.input_name = self.session.get_inputs()[0].name
  342. self.output_name = self.session.get_outputs()[0].name
  343. print(f"ONNX 模型加载成功: {self.model_path}")
  344. except ImportError:
  345. raise ImportError("未安装 onnxruntime,请运行: pip install onnxruntime")
  346. def _load_yolo_model(self):
  347. """加载YOLO11检测模型"""
  348. try:
  349. from ultralytics import YOLO
  350. if self.model_path:
  351. self.model = YOLO(self.model_path)
  352. else:
  353. model_name = f'yolo11{self.model_size}.pt'
  354. self.model = YOLO(model_name)
  355. dummy = np.zeros((640, 640, 3), dtype=np.uint8)
  356. self.model(dummy, device=self.device, verbose=False)
  357. print(f"成功加载YOLO11检测模型 (device={self.device})")
  358. except ImportError:
  359. print("未安装ultralytics,请运行: pip install ultralytics")
  360. self._load_opencv_model()
  361. except Exception as e:
  362. print(f"加载YOLO11模型失败: {e}")
  363. self._load_opencv_model()
  364. def _load_opencv_model(self):
  365. """使用OpenCV加载模型"""
  366. pass
  367. def _letterbox(self, image, size=(640, 640)):
  368. """Letterbox 预处理"""
  369. h0, w0 = image.shape[:2]
  370. ih, iw = size
  371. scale = min(iw / w0, ih / h0)
  372. new_w, new_h = int(w0 * scale), int(h0 * scale)
  373. pad_w = (iw - new_w) // 2
  374. pad_h = (ih - new_h) // 2
  375. resized = cv2.resize(image, (new_w, new_h))
  376. canvas = np.full((ih, iw, 3), 114, dtype=np.uint8)
  377. canvas[pad_h:pad_h+new_h, pad_w:pad_w+new_w] = resized
  378. return canvas, scale, pad_w, pad_h, h0, w0
  379. def _detect_rknn(self, frame: np.ndarray) -> List[DetectedObject]:
  380. """使用 RKNN/ONNX 模型检测"""
  381. results = []
  382. try:
  383. canvas, scale, pad_w, pad_h, h0, w0 = self._letterbox(frame)
  384. if hasattr(self, 'rknn'):
  385. # RKNN
  386. img = canvas[..., ::-1].astype(np.float32) / 255.0
  387. blob = img[None, ...]
  388. outputs = self.rknn.inference(inputs=[blob])
  389. else:
  390. # ONNX
  391. img = canvas[..., ::-1].astype(np.float32) / 255.0
  392. img = img.transpose(2, 0, 1)
  393. blob = img[None, ...]
  394. outputs = self.session.run([self.output_name], {self.input_name: blob})
  395. output = outputs[0]
  396. if len(output.shape) == 3:
  397. output = output[0]
  398. num_boxes = output.shape[1]
  399. conf_threshold = self.config['confidence_threshold']
  400. for i in range(num_boxes):
  401. x_center = float(output[0, i])
  402. y_center = float(output[1, i])
  403. width = float(output[2, i])
  404. height = float(output[3, i])
  405. class_probs = output[4:, i]
  406. best_class = int(np.argmax(class_probs))
  407. confidence = float(class_probs[best_class])
  408. if confidence < conf_threshold:
  409. continue
  410. # 转换到原始图像坐标
  411. x1 = int(((x_center - width / 2) - pad_w) / scale)
  412. y1 = int(((y_center - height / 2) - pad_h) / scale)
  413. x2 = int(((x_center + width / 2) - pad_w) / scale)
  414. y2 = int(((y_center + height / 2) - pad_h) / scale)
  415. x1 = max(0, min(w0, x1))
  416. y1 = max(0, min(h0, y1))
  417. x2 = max(0, min(w0, x2))
  418. y2 = max(0, min(h0, y2))
  419. if x2 - x1 < 10 or y2 - y1 < 10:
  420. continue
  421. # 只检测 person (class 0 in YOLO person model, 但 RKNN safety 模型是 class 3)
  422. # 对于通用检测,尝试获取类别名称
  423. cls_name = str(best_class)
  424. if best_class == 0:
  425. cls_name = 'person'
  426. elif best_class == 3:
  427. cls_name = 'person' # 安全模型中的人
  428. obj = DetectedObject(
  429. class_name=cls_name,
  430. confidence=confidence,
  431. bbox=(x1, y1, x2 - x1, y2 - y1),
  432. center=((x1 + x2) // 2, (y1 + y2) // 2)
  433. )
  434. results.append(obj)
  435. except Exception as e:
  436. print(f"RKNN/ONNX 检测错误: {e}")
  437. return results
  438. def detect(self, frame: np.ndarray) -> List[DetectedObject]:
  439. """
  440. 使用YOLO11检测物体
  441. Args:
  442. frame: 输入图像
  443. Returns:
  444. 检测结果列表
  445. """
  446. if frame is None:
  447. return []
  448. if self.rknn_detector is not None or hasattr(self, 'rknn') or hasattr(self, 'session'):
  449. return self._detect_rknn(frame)
  450. else:
  451. return self._detect_yolo(frame)
  452. def _detect_yolo(self, frame: np.ndarray) -> List[DetectedObject]:
  453. """使用 YOLO 模型检测"""
  454. results = []
  455. try:
  456. detections = self.model(
  457. frame,
  458. device=self.device,
  459. verbose=False,
  460. conf=self.config['confidence_threshold']
  461. )
  462. for det in detections:
  463. boxes = det.boxes
  464. if boxes is None:
  465. continue
  466. for i in range(len(boxes)):
  467. cls_id = int(boxes.cls[i])
  468. cls_name = det.names[cls_id]
  469. if cls_name not in self.config['target_classes']:
  470. continue
  471. conf = float(boxes.conf[i])
  472. xyxy = boxes.xyxy[i].cpu().numpy()
  473. x1, y1, x2, y2 = map(int, xyxy)
  474. width = x2 - x1
  475. height = y2 - y1
  476. if width < 10 or height < 10:
  477. continue
  478. center_x = x1 + width // 2
  479. center_y = y1 + height // 2
  480. obj = DetectedObject(
  481. class_name=cls_name,
  482. confidence=conf,
  483. bbox=(x1, y1, width, height),
  484. center=(center_x, center_y)
  485. )
  486. results.append(obj)
  487. except Exception as e:
  488. print(f"YOLO11检测错误: {e}")
  489. return results
  490. def detect_with_keypoints(self, frame: np.ndarray) -> List[DetectedObject]:
  491. """
  492. 使用YOLO11-pose检测人体并返回关键点
  493. Args:
  494. frame: 输入图像
  495. Returns:
  496. 带关键点的检测结果列表
  497. """
  498. return self.detect(frame)
  499. def detect_persons(self, frame: np.ndarray) -> List[DetectedObject]:
  500. """
  501. 检测人体
  502. Args:
  503. frame: 输入图像
  504. Returns:
  505. 检测到的人体列表
  506. """
  507. results = self.detect(frame)
  508. return [obj for obj in results if obj.class_name == 'person']
  509. def release(self):
  510. """释放模型资源"""
  511. if hasattr(self, 'rknn') and self.rknn:
  512. self.rknn.release()
  513. self.rknn = None
  514. self.model = None
  515. self.session = None
  516. class PersonTracker:
  517. """
  518. 人体跟踪器
  519. 使用简单的质心跟踪算法
  520. """
  521. def __init__(self, max_disappeared: int = 30):
  522. """
  523. 初始化跟踪器
  524. Args:
  525. max_disappeared: 最大消失帧数
  526. """
  527. self.max_disappeared = max_disappeared
  528. self.next_id = 0
  529. self.objects = {} # id -> center
  530. self.disappeared = {} # id -> disappeared count
  531. def update(self, detections: List[DetectedObject]) -> List[DetectedObject]:
  532. """
  533. 更新跟踪状态
  534. Args:
  535. detections: 当前帧检测结果
  536. Returns:
  537. 带有跟踪ID的检测结果
  538. """
  539. # 如果没有检测结果
  540. if len(detections) == 0:
  541. # 标记所有已跟踪对象为消失
  542. for obj_id in list(self.disappeared.keys()):
  543. self.disappeared[obj_id] += 1
  544. if self.disappeared[obj_id] > self.max_disappeared:
  545. self._deregister(obj_id)
  546. return []
  547. # 计算当前检测中心点
  548. input_centers = np.array([d.center for d in detections])
  549. # 如果没有已跟踪对象
  550. if len(self.objects) == 0:
  551. for det in detections:
  552. self._register(det)
  553. else:
  554. # 计算距离矩阵
  555. object_ids = list(self.objects.keys())
  556. object_centers = np.array([self.objects[obj_id] for obj_id in object_ids])
  557. # 计算欧氏距离
  558. distances = np.linalg.norm(
  559. object_centers[:, np.newaxis] - input_centers,
  560. axis=2
  561. )
  562. # 匈牙利算法匹配 (简化版: 贪心匹配)
  563. rows = distances.min(axis=1).argsort()
  564. cols = distances.argmin(axis=1)[rows]
  565. used_rows = set()
  566. used_cols = set()
  567. for (row, col) in zip(rows, cols):
  568. if row in used_rows or col in used_cols:
  569. continue
  570. obj_id = object_ids[row]
  571. self.objects[obj_id] = input_centers[col]
  572. self.disappeared[obj_id] = 0
  573. detections[col].track_id = obj_id
  574. used_rows.add(row)
  575. used_cols.add(col)
  576. # 处理未匹配的已跟踪对象
  577. unused_rows = set(range(len(object_ids))) - used_rows
  578. for row in unused_rows:
  579. obj_id = object_ids[row]
  580. self.disappeared[obj_id] += 1
  581. if self.disappeared[obj_id] > self.max_disappeared:
  582. self._deregister(obj_id)
  583. # 处理未匹配的新检测
  584. unused_cols = set(range(len(input_centers))) - used_cols
  585. for col in unused_cols:
  586. self._register(detections[col])
  587. return [d for d in detections if d.track_id is not None]
  588. def _register(self, detection: DetectedObject):
  589. """注册新对象"""
  590. detection.track_id = self.next_id
  591. self.objects[self.next_id] = detection.center
  592. self.disappeared[self.next_id] = 0
  593. self.next_id += 1
  594. def _deregister(self, obj_id: int):
  595. """注销对象"""
  596. del self.objects[obj_id]
  597. del self.disappeared[obj_id]